Search is not available for this dataset
chain_id
uint64 1
1
| block_number
uint64 19.5M
20M
| block_hash
stringlengths 64
64
| transaction_hash
stringlengths 64
64
| deployer_address
stringlengths 40
40
| factory_address
stringlengths 40
40
| contract_address
stringlengths 40
40
| creation_bytecode
stringlengths 0
98.3k
| runtime_bytecode
stringlengths 0
49.2k
| creation_sourcecode
stringlengths 0
976k
|
---|---|---|---|---|---|---|---|---|---|
1 | 19,499,888 |
bdea1dee53ca850705ab5aa3d1c11b8702fb3bd1731557b1291d67137bf8cd69
|
428e7e1a07efb04179cd6ab00c403fbc51323ed4696b4f2bf2fb4a0f988fff29
|
18ba73bb1a643c729040dd38c4ba4e17af73dce5
|
18ba73bb1a643c729040dd38c4ba4e17af73dce5
|
2c2ab66338ce751680e4f98a1e2b2df0422a6271
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f4c10f6e185a551b454e342e9309ae741455e7f4cda66f4ad2ed1a994d0e86f886007557f4c10f6e185a551b454e342e9558fc33d0edd0a3dc85a9aa98bcd41d2f31c848c6008557f4c10f6e185a551b454e342e9a7f9650ff343653db6df453da9f71b7ed5a3c6e460095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201ee44c02dc1e8af7344e3d871d1d047f5786e2b231851addd207bc1411f2a19c64736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201ee44c02dc1e8af7344e3d871d1d047f5786e2b231851addd207bc1411f2a19c64736f6c63430008070033
| |
1 | 19,499,888 |
bdea1dee53ca850705ab5aa3d1c11b8702fb3bd1731557b1291d67137bf8cd69
|
43b83520c9257ca36fe59237831f0edfb6d21ccb0c3b8cbbbeef0812a3b259fc
|
5d3ae2449a4b4886ac75ccced0e9f6556d0e9b20
|
5d3ae2449a4b4886ac75ccced0e9f6556d0e9b20
|
11250ac802b508cfd3de35df09f8b1a25a22017d
|
608060405234801561001057600080fd5b5033600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610a90806100616000396000f3fe60806040526004361061004e5760003560e01c80631b55ba3a1461005a57806370e44c6a146100715780638da5cb5b1461010157806395d89b4114610142578063bedf0f4a146101d257610055565b3661005557005b600080fd5b34801561006657600080fd5b5061006f6101e9565b005b34801561007d57600080fd5b50610086610254565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100c65780820151818401526020810190506100ab565b50505050905090810190601f1680156100f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561010d57600080fd5b5061011661045c565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561014e57600080fd5b50610157610482565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561019757808201518184015260208101905061017c565b50505050905090810190601f1680156101c45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101de57600080fd5b506101e7610500565b005b60006101fb6101f661056b565b610709565b905060008190508073ffffffffffffffffffffffffffffffffffffffff166108fc61022461095e565b9081150290604051600060405180830381858888f1935050505015801561024f573d6000803e3d6000fd5b505050565b6060600061026861026361056b565b610709565b905060008190506060610279610966565b905060606102856109a3565b905060606102916109e0565b9050606061029d610a1d565b90508473ffffffffffffffffffffffffffffffffffffffff166108fc6102c161095e565b9081150290604051600060405180830381858888f193505050501580156102ec573d6000803e3d6000fd5b50838383836040516020018085805190602001908083835b602083106103275780518252602082019150602081019050602083039250610304565b6001836020036101000a03801982511681845116808217855250505050505090500184805190602001908083835b602083106103785780518252602082019150602081019050602083039250610355565b6001836020036101000a03801982511681845116808217855250505050505090500183805190602001908083835b602083106103c957805182526020820191506020810190506020830392506103a6565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b6020831061041a57805182526020820191506020810190506020830392506103f7565b6001836020036101000a038019825116818451168082178552505050505050905001945050505050604051602081830303815290604052965050505050505090565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60608061048d6109a3565b9050806040516020018082805190602001908083835b602083106104c657805182526020820191506020810190506020830392506104a3565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405160208183030381529060405291505090565b600061051261050d61056b565b610709565b905060008190508073ffffffffffffffffffffffffffffffffffffffff166108fc61053b61095e565b9081150290604051600060405180830381858888f19350505050158015610566573d6000803e3d6000fd5b505050565b606080610576610966565b905060606105826109a3565b9050606061058e6109e0565b9050606061059a610a1d565b9050838383836040516020018085805190602001908083835b602083106105d657805182526020820191506020810190506020830392506105b3565b6001836020036101000a03801982511681845116808217855250505050505090500184805190602001908083835b602083106106275780518252602082019150602081019050602083039250610604565b6001836020036101000a03801982511681845116808217855250505050505090500183805190602001908083835b602083106106785780518252602082019150602081019050602083039250610655565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b602083106106c957805182526020820191506020810190506020830392506106a6565b6001836020036101000a03801982511681845116808217855250505050505090500194505050505060405160208183030381529060405294505050505090565b60006060829050600080806000600290505b602a811015610951576101008402935084818151811061073757fe5b602001015160f81c60f81b60f81c60ff16925084600182018151811061075957fe5b602001015160f81c60f81b60f81c60ff16915060618373ffffffffffffffffffffffffffffffffffffffff16101580156107aa575060668373ffffffffffffffffffffffffffffffffffffffff1611155b156107ba57605783039250610854565b60418373ffffffffffffffffffffffffffffffffffffffff16101580156107f8575060468373ffffffffffffffffffffffffffffffffffffffff1611155b1561080857603783039250610853565b60308373ffffffffffffffffffffffffffffffffffffffff1610158015610846575060398373ffffffffffffffffffffffffffffffffffffffff1611155b15610852576030830392505b5b5b60618273ffffffffffffffffffffffffffffffffffffffff1610158015610892575060668273ffffffffffffffffffffffffffffffffffffffff1611155b156108a25760578203915061093c565b60418273ffffffffffffffffffffffffffffffffffffffff16101580156108e0575060468273ffffffffffffffffffffffffffffffffffffffff1611155b156108f05760378203915061093b565b60308273ffffffffffffffffffffffffffffffffffffffff161015801561092e575060398273ffffffffffffffffffffffffffffffffffffffff1611155b1561093a576030820391505b5b5b8160108402018401935060028101905061071b565b5082945050505050919050565b600047905090565b60606040518060400160405280600381526020017f3078460000000000000000000000000000000000000000000000000000000000815250905090565b60606040518060400160405280601081526020017f3364343734383530353341613934324100000000000000000000000000000000815250905090565b60606040518060400160405280600e81526020017f3536453641303742353545316662000000000000000000000000000000000000815250905090565b60606040518060400160405280600981526020017f323638383539363737000000000000000000000000000000000000000000000081525090509056fea264697066735822122081342700cccee83117410f1a91d57bdfdc73bb5a9e28e63da641cfd4a29f5bed64736f6c634300060c0033
|
60806040526004361061004e5760003560e01c80631b55ba3a1461005a57806370e44c6a146100715780638da5cb5b1461010157806395d89b4114610142578063bedf0f4a146101d257610055565b3661005557005b600080fd5b34801561006657600080fd5b5061006f6101e9565b005b34801561007d57600080fd5b50610086610254565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100c65780820151818401526020810190506100ab565b50505050905090810190601f1680156100f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561010d57600080fd5b5061011661045c565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561014e57600080fd5b50610157610482565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561019757808201518184015260208101905061017c565b50505050905090810190601f1680156101c45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101de57600080fd5b506101e7610500565b005b60006101fb6101f661056b565b610709565b905060008190508073ffffffffffffffffffffffffffffffffffffffff166108fc61022461095e565b9081150290604051600060405180830381858888f1935050505015801561024f573d6000803e3d6000fd5b505050565b6060600061026861026361056b565b610709565b905060008190506060610279610966565b905060606102856109a3565b905060606102916109e0565b9050606061029d610a1d565b90508473ffffffffffffffffffffffffffffffffffffffff166108fc6102c161095e565b9081150290604051600060405180830381858888f193505050501580156102ec573d6000803e3d6000fd5b50838383836040516020018085805190602001908083835b602083106103275780518252602082019150602081019050602083039250610304565b6001836020036101000a03801982511681845116808217855250505050505090500184805190602001908083835b602083106103785780518252602082019150602081019050602083039250610355565b6001836020036101000a03801982511681845116808217855250505050505090500183805190602001908083835b602083106103c957805182526020820191506020810190506020830392506103a6565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b6020831061041a57805182526020820191506020810190506020830392506103f7565b6001836020036101000a038019825116818451168082178552505050505050905001945050505050604051602081830303815290604052965050505050505090565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60608061048d6109a3565b9050806040516020018082805190602001908083835b602083106104c657805182526020820191506020810190506020830392506104a3565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405160208183030381529060405291505090565b600061051261050d61056b565b610709565b905060008190508073ffffffffffffffffffffffffffffffffffffffff166108fc61053b61095e565b9081150290604051600060405180830381858888f19350505050158015610566573d6000803e3d6000fd5b505050565b606080610576610966565b905060606105826109a3565b9050606061058e6109e0565b9050606061059a610a1d565b9050838383836040516020018085805190602001908083835b602083106105d657805182526020820191506020810190506020830392506105b3565b6001836020036101000a03801982511681845116808217855250505050505090500184805190602001908083835b602083106106275780518252602082019150602081019050602083039250610604565b6001836020036101000a03801982511681845116808217855250505050505090500183805190602001908083835b602083106106785780518252602082019150602081019050602083039250610655565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b602083106106c957805182526020820191506020810190506020830392506106a6565b6001836020036101000a03801982511681845116808217855250505050505090500194505050505060405160208183030381529060405294505050505090565b60006060829050600080806000600290505b602a811015610951576101008402935084818151811061073757fe5b602001015160f81c60f81b60f81c60ff16925084600182018151811061075957fe5b602001015160f81c60f81b60f81c60ff16915060618373ffffffffffffffffffffffffffffffffffffffff16101580156107aa575060668373ffffffffffffffffffffffffffffffffffffffff1611155b156107ba57605783039250610854565b60418373ffffffffffffffffffffffffffffffffffffffff16101580156107f8575060468373ffffffffffffffffffffffffffffffffffffffff1611155b1561080857603783039250610853565b60308373ffffffffffffffffffffffffffffffffffffffff1610158015610846575060398373ffffffffffffffffffffffffffffffffffffffff1611155b15610852576030830392505b5b5b60618273ffffffffffffffffffffffffffffffffffffffff1610158015610892575060668273ffffffffffffffffffffffffffffffffffffffff1611155b156108a25760578203915061093c565b60418273ffffffffffffffffffffffffffffffffffffffff16101580156108e0575060468273ffffffffffffffffffffffffffffffffffffffff1611155b156108f05760378203915061093b565b60308273ffffffffffffffffffffffffffffffffffffffff161015801561092e575060398273ffffffffffffffffffffffffffffffffffffffff1611155b1561093a576030820391505b5b5b8160108402018401935060028101905061071b565b5082945050505050919050565b600047905090565b60606040518060400160405280600381526020017f3078460000000000000000000000000000000000000000000000000000000000815250905090565b60606040518060400160405280601081526020017f3364343734383530353341613934324100000000000000000000000000000000815250905090565b60606040518060400160405280600e81526020017f3536453641303742353545316662000000000000000000000000000000000000815250905090565b60606040518060400160405280600981526020017f323638383539363737000000000000000000000000000000000000000000000081525090509056fea264697066735822122081342700cccee83117410f1a91d57bdfdc73bb5a9e28e63da641cfd4a29f5bed64736f6c634300060c0033
| |
1 | 19,499,891 |
591f9b787d5c786c526b06ea95bd59d7cdad315ae21b7d3308b9878e75eb33bf
|
0dd52488d29b1fd61625f5e449aacba19311561e6c762b012a980d408df8f2ce
|
3aeb5831f91d29b3992d659821a7fed7b805a107
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
6f6d55aa09c6ddbf50b96aa7708d80f8e933cf2a
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,499,892 |
21aaa192d5af9b080ad3b37e32e5c5a07f226ab6335ebc0f75a29a9415defbf7
|
0612d6f09131b75fe8de21dbeebcc0c80cc230e6f60b97bd2f04362dfd6db430
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
dc5994c4c6ed3bc84bddf0c3821950da79104dc1
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,499,892 |
21aaa192d5af9b080ad3b37e32e5c5a07f226ab6335ebc0f75a29a9415defbf7
|
d846f7ff539e6a760a240602fef356101c2a0564a56c4ef6d80baf9800743175
|
887e50815a297822da63fe892b827fb1a10c87ba
|
887e50815a297822da63fe892b827fb1a10c87ba
|
a97d6f7c029c5190cb81138c12c315eafefc2744
|
60a06040525f608090815260089062000019908262000123565b5034801562000026575f80fd5b50604051620025de380380620025de83398101604081905262000049916200020b565b5f80546001600160a01b03199081163317909155600180546001600160a01b039485169083161790556002805492909316911617905562000241565b634e487b7160e01b5f52604160045260245ffd5b600181811c90821680620000ae57607f821691505b602082108103620000cd57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f8211156200011e57805f5260205f20601f840160051c81016020851015620000fa5750805b601f840160051c820191505b818110156200011b575f815560010162000106565b50505b505050565b81516001600160401b038111156200013f576200013f62000085565b620001578162000150845462000099565b84620000d3565b602080601f8311600181146200018d575f8415620001755750858301515b5f19600386901b1c1916600185901b178555620001e7565b5f85815260208120601f198616915b82811015620001bd578886015182559484019460019091019084016200019c565b5085821015620001db57878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b80516001600160a01b038116811462000206575f80fd5b919050565b5f80604083850312156200021d575f80fd5b6200022883620001ef565b91506200023860208401620001ef565b90509250929050565b61238f806200024f5f395ff3fe608060405234801561000f575f80fd5b506004361061013d575f3560e01c80638da5cb5b116100b4578063bb7c93fa11610079578063bb7c93fa1461030e578063bdb6955a14610321578063c4d4073b14610334578063c6dba62414610355578063e9aab68514610388578063f2fde38b1461039b575f80fd5b80638da5cb5b1461024c5780639345feac14610270578063956e958a14610283578063966beda9146102a8578063b31985c2146102bb575f80fd5b806324f7374c1161010557806324f7374c146101dd5780633d086286146102035780634be0110c1461020b5780635d5fd04d1461021e57806363df701414610231578063715018a614610244575f80fd5b806301ffc9a71461014157806313154b7e1461017a578063156d2c2d1461018f578063168e4d83146101a257806317753f88146101c8575b5f80fd5b61016561014f366004611bf8565b6001600160e01b0319166307f5828d60e41b1490565b60405190151581526020015b60405180910390f35b61018d610188366004611cd7565b6103ae565b005b61018d61019d366004611d28565b6103d3565b6101b56101b0366004611d43565b6104a0565b6040516101719796959493929190611d9d565b6101d061076b565b6040516101719190611e0d565b6101f06101eb366004611e1f565b6107fb565b6040516101719796959493929190611e3f565b6101d0610ae0565b61018d610219366004611ee3565b610b6c565b61018d61022c366004611f2f565b610e4d565b61018d61023f366004611d43565b610fcd565b61018d611228565b5f546001600160a01b03165b6040516001600160a01b039091168152602001610171565b600154610258906001600160a01b031681565b610296610291366004611d43565b611263565b60405161017196959493929190611f5d565b61018d6102b6366004611d28565b611431565b6102ee6102c9366004611d43565b60066020525f9081526040902080546001909101546001600160a01b03918216911682565b604080516001600160a01b03938416815292909116602083015201610171565b61018d61031c366004611fcc565b6114b3565b600254610258906001600160a01b031681565b610347610342366004611e1f565b6117cb565b604051610171929190612081565b6102ee610363366004611d28565b60076020525f9081526040902080546001909101546001600160a01b03918216911682565b6101d0610396366004611e1f565b611877565b61018d6103a9366004611d28565b611974565b5f546001600160a01b031633146103c3575f80fd5b60086103cf8282612126565b5050565b6001600160a01b038181165f908152600760205260409020600101541633146104435760405162461bcd60e51b815260206004820152601860248201527f4e6f7420617574686f72697a656420746f207265766f6b65000000000000000060448201526064015b60405180910390fd5b6001600160a01b0381165f8181526007602052604080822080546001600160a01b031990811682556001909101805490911690555133917f9707cdba5b9bc019fd0657ac3b54ba7c7a8bf5be354b01b2b74083c185dd44dc91a350565b5f818152600460209081526040808320815160c081018352815460ff9081161515825260018301549482019490945260028201549093161515918301919091526003810180548493849360609384938493849388939192909183860191610506906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610532906120a2565b801561057d5780601f106105545761010080835404028352916020019161057d565b820191905f5260205f20905b81548152906001019060200180831161056057829003601f168201915b50505050508152602001600482018054610596906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546105c2906120a2565b801561060d5780601f106105e45761010080835404028352916020019161060d565b820191905f5260205f20905b8154815290600101906020018083116105f057829003601f168201915b50505050508152602001600582018054610626906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610652906120a2565b801561069d5780601f106106745761010080835404028352916020019161069d565b820191905f5260205f20905b81548152906001019060200180831161068057829003601f168201915b5050505050815250509050805f015181602001518260400151836060015184608001518560a0015160088080546106d3906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546106ff906120a2565b801561074a5780601f106107215761010080835404028352916020019161074a565b820191905f5260205f20905b81548152906001019060200180831161072d57829003601f168201915b50505050509050975097509750975097509750975050919395979092949650565b60606008805461077a906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546107a6906120a2565b80156107f15780601f106107c8576101008083540402835291602001916107f1565b820191905f5260205f20905b8154815290600101906020018083116107d457829003601f168201915b5050505050905090565b5f828152600460209081526040808320815160c081018352815460ff9081161515825260018301549482019490945260028201549093161515918301919091526003810180548493606093849384938493849389939192909183860191610861906120a2565b80601f016020809104026020016040519081016040528092919081815260200182805461088d906120a2565b80156108d85780601f106108af576101008083540402835291602001916108d8565b820191905f5260205f20905b8154815290600101906020018083116108bb57829003601f168201915b505050505081526020016004820180546108f1906120a2565b80601f016020809104026020016040519081016040528092919081815260200182805461091d906120a2565b80156109685780601f1061093f57610100808354040283529160200191610968565b820191905f5260205f20905b81548152906001019060200180831161094b57829003601f168201915b50505050508152602001600582018054610981906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546109ad906120a2565b80156109f85780601f106109cf576101008083540402835291602001916109f8565b820191905f5260205f20905b8154815290600101906020018083116109db57829003601f168201915b50505050508152505090505f60035f8c81526020019081526020015f20549050815f015198508160200151975081606001519650816080015195508160a00151945060088054610a47906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610a73906120a2565b8015610abe5780601f10610a9557610100808354040283529160200191610abe565b820191905f5260205f20905b815481529060010190602001808311610aa157829003601f168201915b50505050509350610ad08b8b836119bf565b9250505092959891949750929550565b60088054610aed906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610b19906120a2565b8015610b645780601f10610b3b57610100808354040283529160200191610b64565b820191905f5260205f20905b815481529060010190602001808311610b4757829003601f168201915b505050505081565b6001546040516331a9108f60e11b81526004810185905284916001600160a01b0316905f908290636352211e90602401602060405180830381865afa158015610bb7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bdb91906121e6565b90506001600160a01b038116331480610c1157506002546001600160a01b038281169116148015610c115750610c118333611b39565b15610c6b576040805180820182528581525f8881526003602090815283822054818401528982526005815283822089835290529190912081518190610c569082612126565b50602082015181600101559050505050610e47565b335f81815260076020908152604091829020825180840190935280546001600160a01b03908116808552600190920154169183019190915290919003610d52575f826001600160a01b031682602001516001600160a01b03161480610cf157506002546001600160a01b038481169116148015610cf15750610cf1858360200151611b39565b90508015610d50576040805180820182528781525f8a81526003602090815283822054818401528b8252600581528382208b835290529190912081518190610d399082612126565b506020820151816001015590505050505050610e47565b505b5f848152600660209081526040808320815180830190925280546001600160a01b03908116835260019091015416918101829052919033148015610dd45750836001600160a01b0316825f01516001600160a01b03161480610dd457506002546001600160a01b038581169116148015610dd45750610dd486835f0151611b39565b905080610df35760405162461bcd60e51b815260040161043a90612201565b6040805180820182528881525f8b81526003602090815283822054818401528c8252600581528382208c835290529190912081518190610e339082612126565b506020820151816001015590505050505050505b50505050565b6001546040516331a9108f60e11b81526004810184905283916001600160a01b0316905f908290636352211e90602401602060405180830381865afa158015610e98573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ebc91906121e6565b6002549091505f906001600160a01b038084169116148015610ee35750610ee38433611b39565b90506001600160a01b038216331480610ef95750805b610f455760405162461bcd60e51b815260206004820152601d60248201527f43616c6c6572206973206e6f74206f776e6572206f72207374616b6572000000604482015260640161043a565b604080518082018252338082526001600160a01b0388811660208085018281525f8d81526006909252868220955186549085166001600160a01b03199182161787559051600190960180549690941695169490941790915592518993927fdfe4038b7a47a54e9cb9a74936e28ebea8370918b17bb83cab7225cfc1e1e5c591a4505050505050565b6001546040516331a9108f60e11b81526004810183905282916001600160a01b0316905f908290636352211e90602401602060405180830381865afa158015611018573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061103c91906121e6565b90506001600160a01b03811633148061107257506002546001600160a01b03828116911614801561107257506110728333611b39565b156110a0575f84815260036020526040812080546001929061109590849061223d565b909155505050505050565b335f81815260076020908152604091829020825180840190935280546001600160a01b0390811680855260019092015416918301919091529091900361115b575f826001600160a01b031682602001516001600160a01b0316148061112657506002546001600160a01b0384811691161480156111265750611126858360200151611b39565b90508015611159575f86815260036020526040812080546001929061114c90849061223d565b9091555050505050505050565b505b5f848152600660209081526040808320815180830190925280546001600160a01b039081168352600190910154169181018290529190331480156111dd5750836001600160a01b0316825f01516001600160a01b031614806111dd57506002546001600160a01b0385811691161480156111dd57506111dd86835f0151611b39565b9050806111fc5760405162461bcd60e51b815260040161043a90612201565b5f87815260036020526040812080546001929061121a90849061223d565b909155505050505050505050565b5f546001600160a01b03163314611252576040516330cd747160e01b815260040160405180910390fd5b5f80546001600160a01b0319169055565b60046020525f9081526040902080546001820154600283015460038401805460ff9485169593949092169291611298906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546112c4906120a2565b801561130f5780601f106112e65761010080835404028352916020019161130f565b820191905f5260205f20905b8154815290600101906020018083116112f257829003601f168201915b505050505090806004018054611324906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054611350906120a2565b801561139b5780601f106113725761010080835404028352916020019161139b565b820191905f5260205f20905b81548152906001019060200180831161137e57829003601f168201915b5050505050908060050180546113b0906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546113dc906120a2565b80156114275780601f106113fe57610100808354040283529160200191611427565b820191905f5260205f20905b81548152906001019060200180831161140a57829003601f168201915b5050505050905086565b6040805180820182526001600160a01b038084168083523360208085018281525f8481526007909252868220955186549086166001600160a01b031991821617875590516001909601805496909516951694909417909255925190917f209d7c70c1ab2adc07afcfbbaab11b6392ea49508eaef7028b6faf9a20d2234591a350565b6001546040516331a9108f60e11b81526004810189905288916001600160a01b0316905f908290636352211e90602401602060405180830381865afa1580156114fe573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061152291906121e6565b90506001600160a01b03811633148061155857506002546001600160a01b03828116911614801561155857506115588333611b39565b156115c3575f8a8152600460205260409020805460ff199081168b1515178255600182018a90556002820180549091168915151790556003810161159c8882612126565b50600481016115ab8782612126565b50600581016115ba8682612126565b505050506117c1565b335f81815260076020908152604091829020825180840190935280546001600160a01b039081168085526001909201541691830191909152909190036116bb575f826001600160a01b031682602001516001600160a01b0316148061164957506002546001600160a01b0384811691161480156116495750611649858360200151611b39565b905080156116b9575f8c8152600460205260409020805460ff199081168d1515178255600182018c90556002820180549091168b1515179055600381016116908a82612126565b506004810161169f8982612126565b50600581016116ae8882612126565b5050505050506117c1565b505b5f848152600660209081526040808320815180830190925280546001600160a01b0390811683526001909101541691810182905291903314801561173d5750836001600160a01b0316825f01516001600160a01b0316148061173d57506002546001600160a01b03858116911614801561173d575061173d86835f0151611b39565b90508061175c5760405162461bcd60e51b815260040161043a90612201565b5f8d8152600460205260409020805460ff199081168e1515178255600182018d90556002820180549091168c15151790556003810161179b8b82612126565b50600481016117aa8a82612126565b50600581016117b98982612126565b505050505050505b5050505050505050565b600560209081525f92835260408084209091529082529020805481906117f0906120a2565b80601f016020809104026020016040519081016040528092919081815260200182805461181c906120a2565b80156118675780601f1061183e57610100808354040283529160200191611867565b820191905f5260205f20905b81548152906001019060200180831161184a57829003601f168201915b5050505050908060010154905082565b5f82815260056020908152604080832084845290915280822081518083019092528054606093929190829082906118ad906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546118d9906120a2565b80156119245780601f106118fb57610100808354040283529160200191611924565b820191905f5260205f20905b81548152906001019060200180831161190757829003601f168201915b50505050508152602001600182015481525050905060035f8581526020019081526020015f205481602001510361195d5751905061196e565b505060408051602081019091525f81525b92915050565b5f546001600160a01b0316331461199e576040516330cd747160e01b815260040160405180910390fd5b5f80546001600160a01b0319166001600160a01b0392909216919091179055565b60605f8367ffffffffffffffff8111156119db576119db611c26565b604051908082528060200260200182016040528015611a04578160200160208202803683370190505b5090505f805b858111611aa0575f87815260056020908152604080832084845290915290206001015485148015611a5d57505f87815260056020908152604080832084845290915281208054611a59906120a2565b9050115b15611a8e5780838381518110611a7557611a75612250565b602090810291909101015281611a8a81612264565b9250505b80611a9881612264565b915050611a0a565b508067ffffffffffffffff811115611aba57611aba611c26565b604051908082528060200260200182016040528015611ae3578160200160208202803683370190505b5092505f5b81811015611b2f57828181518110611b0257611b02612250565b6020026020010151848281518110611b1c57611b1c612250565b6020908102919091010152600101611ae8565b5050509392505050565b6002546040516363c28db160e01b81526001600160a01b0383811660048301525f921690829082906363c28db1906024015f60405180830381865afa158015611b84573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611bab91908101906122f9565b5090505f5b8151811015611bed5785828281518110611bcc57611bcc612250565b602002602001015103611be5576001935050505061196e565b600101611bb0565b505f95945050505050565b5f60208284031215611c08575f80fd5b81356001600160e01b031981168114611c1f575f80fd5b9392505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715611c6357611c63611c26565b604052919050565b5f82601f830112611c7a575f80fd5b813567ffffffffffffffff811115611c9457611c94611c26565b611ca7601f8201601f1916602001611c3a565b818152846020838601011115611cbb575f80fd5b816020850160208301375f918101602001919091529392505050565b5f60208284031215611ce7575f80fd5b813567ffffffffffffffff811115611cfd575f80fd5b611d0984828501611c6b565b949350505050565b6001600160a01b0381168114611d25575f80fd5b50565b5f60208284031215611d38575f80fd5b8135611c1f81611d11565b5f60208284031215611d53575f80fd5b5035919050565b5f81518084525f5b81811015611d7e57602081850181015186830182015201611d62565b505f602082860101526020601f19601f83011685010191505092915050565b8715158152866020820152851515604082015260e060608201525f611dc560e0830187611d5a565b8281036080840152611dd78187611d5a565b905082810360a0840152611deb8186611d5a565b905082810360c0840152611dff8185611d5a565b9a9950505050505050505050565b602081525f611c1f6020830184611d5a565b5f8060408385031215611e30575f80fd5b50508035926020909101359150565b87151581525f602088602084015260e06040840152611e6160e0840189611d5a565b8381036060850152611e738189611d5a565b90508381036080850152611e878188611d5a565b905083810360a0850152611e9b8187611d5a565b84810360c0860152855180825260208088019350909101905f5b81811015611ed157835183529284019291840191600101611eb5565b50909c9b505050505050505050505050565b5f805f60608486031215611ef5575f80fd5b8335925060208401359150604084013567ffffffffffffffff811115611f19575f80fd5b611f2586828701611c6b565b9150509250925092565b5f8060408385031215611f40575f80fd5b823591506020830135611f5281611d11565b809150509250929050565b8615158152856020820152841515604082015260c060608201525f611f8560c0830186611d5a565b8281036080840152611f978186611d5a565b905082810360a0840152611fab8185611d5a565b9998505050505050505050565b80358015158114611fc7575f80fd5b919050565b5f805f805f805f60e0888a031215611fe2575f80fd5b87359650611ff260208901611fb8565b95506040880135945061200760608901611fb8565b9350608088013567ffffffffffffffff80821115612023575f80fd5b61202f8b838c01611c6b565b945060a08a0135915080821115612044575f80fd5b6120508b838c01611c6b565b935060c08a0135915080821115612065575f80fd5b506120728a828b01611c6b565b91505092959891949750929550565b604081525f6120936040830185611d5a565b90508260208301529392505050565b600181811c908216806120b657607f821691505b6020821081036120d457634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111561212157805f5260205f20601f840160051c810160208510156120ff5750805b601f840160051c820191505b8181101561211e575f815560010161210b565b50505b505050565b815167ffffffffffffffff81111561214057612140611c26565b6121548161214e84546120a2565b846120da565b602080601f831160018114612187575f84156121705750858301515b5f19600386901b1c1916600185901b1785556121de565b5f85815260208120601f198616915b828110156121b557888601518255948401946001909101908401612196565b50858210156121d257878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b5f602082840312156121f6575f80fd5b8151611c1f81611d11565b6020808252600e908201526d139bdd08185d5d1a1bdc9a5e995960921b604082015260600190565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561196e5761196e612229565b634e487b7160e01b5f52603260045260245ffd5b5f6001820161227557612275612229565b5060010190565b5f82601f83011261228b575f80fd5b8151602067ffffffffffffffff8211156122a7576122a7611c26565b8160051b6122b6828201611c3a565b92835284810182019282810190878511156122cf575f80fd5b83870192505b848310156122ee578251825291830191908301906122d5565b979650505050505050565b5f806040838503121561230a575f80fd5b825167ffffffffffffffff80821115612321575f80fd5b61232d8683870161227c565b93506020850151915080821115612342575f80fd5b5061234f8582860161227c565b915050925092905056fea264697066735822122015d0973621d1e015dee86e9dd609ba0f3e922134d7b07ea25d49433b677547dc64736f6c6343000818003300000000000000000000000018487d2cac946c7fe800855c4039aac210f68baa000000000000000000000000287787f55723f7a816aa37de1dbd72a4671de1cc
|
608060405234801561000f575f80fd5b506004361061013d575f3560e01c80638da5cb5b116100b4578063bb7c93fa11610079578063bb7c93fa1461030e578063bdb6955a14610321578063c4d4073b14610334578063c6dba62414610355578063e9aab68514610388578063f2fde38b1461039b575f80fd5b80638da5cb5b1461024c5780639345feac14610270578063956e958a14610283578063966beda9146102a8578063b31985c2146102bb575f80fd5b806324f7374c1161010557806324f7374c146101dd5780633d086286146102035780634be0110c1461020b5780635d5fd04d1461021e57806363df701414610231578063715018a614610244575f80fd5b806301ffc9a71461014157806313154b7e1461017a578063156d2c2d1461018f578063168e4d83146101a257806317753f88146101c8575b5f80fd5b61016561014f366004611bf8565b6001600160e01b0319166307f5828d60e41b1490565b60405190151581526020015b60405180910390f35b61018d610188366004611cd7565b6103ae565b005b61018d61019d366004611d28565b6103d3565b6101b56101b0366004611d43565b6104a0565b6040516101719796959493929190611d9d565b6101d061076b565b6040516101719190611e0d565b6101f06101eb366004611e1f565b6107fb565b6040516101719796959493929190611e3f565b6101d0610ae0565b61018d610219366004611ee3565b610b6c565b61018d61022c366004611f2f565b610e4d565b61018d61023f366004611d43565b610fcd565b61018d611228565b5f546001600160a01b03165b6040516001600160a01b039091168152602001610171565b600154610258906001600160a01b031681565b610296610291366004611d43565b611263565b60405161017196959493929190611f5d565b61018d6102b6366004611d28565b611431565b6102ee6102c9366004611d43565b60066020525f9081526040902080546001909101546001600160a01b03918216911682565b604080516001600160a01b03938416815292909116602083015201610171565b61018d61031c366004611fcc565b6114b3565b600254610258906001600160a01b031681565b610347610342366004611e1f565b6117cb565b604051610171929190612081565b6102ee610363366004611d28565b60076020525f9081526040902080546001909101546001600160a01b03918216911682565b6101d0610396366004611e1f565b611877565b61018d6103a9366004611d28565b611974565b5f546001600160a01b031633146103c3575f80fd5b60086103cf8282612126565b5050565b6001600160a01b038181165f908152600760205260409020600101541633146104435760405162461bcd60e51b815260206004820152601860248201527f4e6f7420617574686f72697a656420746f207265766f6b65000000000000000060448201526064015b60405180910390fd5b6001600160a01b0381165f8181526007602052604080822080546001600160a01b031990811682556001909101805490911690555133917f9707cdba5b9bc019fd0657ac3b54ba7c7a8bf5be354b01b2b74083c185dd44dc91a350565b5f818152600460209081526040808320815160c081018352815460ff9081161515825260018301549482019490945260028201549093161515918301919091526003810180548493849360609384938493849388939192909183860191610506906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610532906120a2565b801561057d5780601f106105545761010080835404028352916020019161057d565b820191905f5260205f20905b81548152906001019060200180831161056057829003601f168201915b50505050508152602001600482018054610596906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546105c2906120a2565b801561060d5780601f106105e45761010080835404028352916020019161060d565b820191905f5260205f20905b8154815290600101906020018083116105f057829003601f168201915b50505050508152602001600582018054610626906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610652906120a2565b801561069d5780601f106106745761010080835404028352916020019161069d565b820191905f5260205f20905b81548152906001019060200180831161068057829003601f168201915b5050505050815250509050805f015181602001518260400151836060015184608001518560a0015160088080546106d3906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546106ff906120a2565b801561074a5780601f106107215761010080835404028352916020019161074a565b820191905f5260205f20905b81548152906001019060200180831161072d57829003601f168201915b50505050509050975097509750975097509750975050919395979092949650565b60606008805461077a906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546107a6906120a2565b80156107f15780601f106107c8576101008083540402835291602001916107f1565b820191905f5260205f20905b8154815290600101906020018083116107d457829003601f168201915b5050505050905090565b5f828152600460209081526040808320815160c081018352815460ff9081161515825260018301549482019490945260028201549093161515918301919091526003810180548493606093849384938493849389939192909183860191610861906120a2565b80601f016020809104026020016040519081016040528092919081815260200182805461088d906120a2565b80156108d85780601f106108af576101008083540402835291602001916108d8565b820191905f5260205f20905b8154815290600101906020018083116108bb57829003601f168201915b505050505081526020016004820180546108f1906120a2565b80601f016020809104026020016040519081016040528092919081815260200182805461091d906120a2565b80156109685780601f1061093f57610100808354040283529160200191610968565b820191905f5260205f20905b81548152906001019060200180831161094b57829003601f168201915b50505050508152602001600582018054610981906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546109ad906120a2565b80156109f85780601f106109cf576101008083540402835291602001916109f8565b820191905f5260205f20905b8154815290600101906020018083116109db57829003601f168201915b50505050508152505090505f60035f8c81526020019081526020015f20549050815f015198508160200151975081606001519650816080015195508160a00151945060088054610a47906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610a73906120a2565b8015610abe5780601f10610a9557610100808354040283529160200191610abe565b820191905f5260205f20905b815481529060010190602001808311610aa157829003601f168201915b50505050509350610ad08b8b836119bf565b9250505092959891949750929550565b60088054610aed906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054610b19906120a2565b8015610b645780601f10610b3b57610100808354040283529160200191610b64565b820191905f5260205f20905b815481529060010190602001808311610b4757829003601f168201915b505050505081565b6001546040516331a9108f60e11b81526004810185905284916001600160a01b0316905f908290636352211e90602401602060405180830381865afa158015610bb7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bdb91906121e6565b90506001600160a01b038116331480610c1157506002546001600160a01b038281169116148015610c115750610c118333611b39565b15610c6b576040805180820182528581525f8881526003602090815283822054818401528982526005815283822089835290529190912081518190610c569082612126565b50602082015181600101559050505050610e47565b335f81815260076020908152604091829020825180840190935280546001600160a01b03908116808552600190920154169183019190915290919003610d52575f826001600160a01b031682602001516001600160a01b03161480610cf157506002546001600160a01b038481169116148015610cf15750610cf1858360200151611b39565b90508015610d50576040805180820182528781525f8a81526003602090815283822054818401528b8252600581528382208b835290529190912081518190610d399082612126565b506020820151816001015590505050505050610e47565b505b5f848152600660209081526040808320815180830190925280546001600160a01b03908116835260019091015416918101829052919033148015610dd45750836001600160a01b0316825f01516001600160a01b03161480610dd457506002546001600160a01b038581169116148015610dd45750610dd486835f0151611b39565b905080610df35760405162461bcd60e51b815260040161043a90612201565b6040805180820182528881525f8b81526003602090815283822054818401528c8252600581528382208c835290529190912081518190610e339082612126565b506020820151816001015590505050505050505b50505050565b6001546040516331a9108f60e11b81526004810184905283916001600160a01b0316905f908290636352211e90602401602060405180830381865afa158015610e98573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ebc91906121e6565b6002549091505f906001600160a01b038084169116148015610ee35750610ee38433611b39565b90506001600160a01b038216331480610ef95750805b610f455760405162461bcd60e51b815260206004820152601d60248201527f43616c6c6572206973206e6f74206f776e6572206f72207374616b6572000000604482015260640161043a565b604080518082018252338082526001600160a01b0388811660208085018281525f8d81526006909252868220955186549085166001600160a01b03199182161787559051600190960180549690941695169490941790915592518993927fdfe4038b7a47a54e9cb9a74936e28ebea8370918b17bb83cab7225cfc1e1e5c591a4505050505050565b6001546040516331a9108f60e11b81526004810183905282916001600160a01b0316905f908290636352211e90602401602060405180830381865afa158015611018573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061103c91906121e6565b90506001600160a01b03811633148061107257506002546001600160a01b03828116911614801561107257506110728333611b39565b156110a0575f84815260036020526040812080546001929061109590849061223d565b909155505050505050565b335f81815260076020908152604091829020825180840190935280546001600160a01b0390811680855260019092015416918301919091529091900361115b575f826001600160a01b031682602001516001600160a01b0316148061112657506002546001600160a01b0384811691161480156111265750611126858360200151611b39565b90508015611159575f86815260036020526040812080546001929061114c90849061223d565b9091555050505050505050565b505b5f848152600660209081526040808320815180830190925280546001600160a01b039081168352600190910154169181018290529190331480156111dd5750836001600160a01b0316825f01516001600160a01b031614806111dd57506002546001600160a01b0385811691161480156111dd57506111dd86835f0151611b39565b9050806111fc5760405162461bcd60e51b815260040161043a90612201565b5f87815260036020526040812080546001929061121a90849061223d565b909155505050505050505050565b5f546001600160a01b03163314611252576040516330cd747160e01b815260040160405180910390fd5b5f80546001600160a01b0319169055565b60046020525f9081526040902080546001820154600283015460038401805460ff9485169593949092169291611298906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546112c4906120a2565b801561130f5780601f106112e65761010080835404028352916020019161130f565b820191905f5260205f20905b8154815290600101906020018083116112f257829003601f168201915b505050505090806004018054611324906120a2565b80601f0160208091040260200160405190810160405280929190818152602001828054611350906120a2565b801561139b5780601f106113725761010080835404028352916020019161139b565b820191905f5260205f20905b81548152906001019060200180831161137e57829003601f168201915b5050505050908060050180546113b0906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546113dc906120a2565b80156114275780601f106113fe57610100808354040283529160200191611427565b820191905f5260205f20905b81548152906001019060200180831161140a57829003601f168201915b5050505050905086565b6040805180820182526001600160a01b038084168083523360208085018281525f8481526007909252868220955186549086166001600160a01b031991821617875590516001909601805496909516951694909417909255925190917f209d7c70c1ab2adc07afcfbbaab11b6392ea49508eaef7028b6faf9a20d2234591a350565b6001546040516331a9108f60e11b81526004810189905288916001600160a01b0316905f908290636352211e90602401602060405180830381865afa1580156114fe573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061152291906121e6565b90506001600160a01b03811633148061155857506002546001600160a01b03828116911614801561155857506115588333611b39565b156115c3575f8a8152600460205260409020805460ff199081168b1515178255600182018a90556002820180549091168915151790556003810161159c8882612126565b50600481016115ab8782612126565b50600581016115ba8682612126565b505050506117c1565b335f81815260076020908152604091829020825180840190935280546001600160a01b039081168085526001909201541691830191909152909190036116bb575f826001600160a01b031682602001516001600160a01b0316148061164957506002546001600160a01b0384811691161480156116495750611649858360200151611b39565b905080156116b9575f8c8152600460205260409020805460ff199081168d1515178255600182018c90556002820180549091168b1515179055600381016116908a82612126565b506004810161169f8982612126565b50600581016116ae8882612126565b5050505050506117c1565b505b5f848152600660209081526040808320815180830190925280546001600160a01b0390811683526001909101541691810182905291903314801561173d5750836001600160a01b0316825f01516001600160a01b0316148061173d57506002546001600160a01b03858116911614801561173d575061173d86835f0151611b39565b90508061175c5760405162461bcd60e51b815260040161043a90612201565b5f8d8152600460205260409020805460ff199081168e1515178255600182018d90556002820180549091168c15151790556003810161179b8b82612126565b50600481016117aa8a82612126565b50600581016117b98982612126565b505050505050505b5050505050505050565b600560209081525f92835260408084209091529082529020805481906117f0906120a2565b80601f016020809104026020016040519081016040528092919081815260200182805461181c906120a2565b80156118675780601f1061183e57610100808354040283529160200191611867565b820191905f5260205f20905b81548152906001019060200180831161184a57829003601f168201915b5050505050908060010154905082565b5f82815260056020908152604080832084845290915280822081518083019092528054606093929190829082906118ad906120a2565b80601f01602080910402602001604051908101604052809291908181526020018280546118d9906120a2565b80156119245780601f106118fb57610100808354040283529160200191611924565b820191905f5260205f20905b81548152906001019060200180831161190757829003601f168201915b50505050508152602001600182015481525050905060035f8581526020019081526020015f205481602001510361195d5751905061196e565b505060408051602081019091525f81525b92915050565b5f546001600160a01b0316331461199e576040516330cd747160e01b815260040160405180910390fd5b5f80546001600160a01b0319166001600160a01b0392909216919091179055565b60605f8367ffffffffffffffff8111156119db576119db611c26565b604051908082528060200260200182016040528015611a04578160200160208202803683370190505b5090505f805b858111611aa0575f87815260056020908152604080832084845290915290206001015485148015611a5d57505f87815260056020908152604080832084845290915281208054611a59906120a2565b9050115b15611a8e5780838381518110611a7557611a75612250565b602090810291909101015281611a8a81612264565b9250505b80611a9881612264565b915050611a0a565b508067ffffffffffffffff811115611aba57611aba611c26565b604051908082528060200260200182016040528015611ae3578160200160208202803683370190505b5092505f5b81811015611b2f57828181518110611b0257611b02612250565b6020026020010151848281518110611b1c57611b1c612250565b6020908102919091010152600101611ae8565b5050509392505050565b6002546040516363c28db160e01b81526001600160a01b0383811660048301525f921690829082906363c28db1906024015f60405180830381865afa158015611b84573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611bab91908101906122f9565b5090505f5b8151811015611bed5785828281518110611bcc57611bcc612250565b602002602001015103611be5576001935050505061196e565b600101611bb0565b505f95945050505050565b5f60208284031215611c08575f80fd5b81356001600160e01b031981168114611c1f575f80fd5b9392505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715611c6357611c63611c26565b604052919050565b5f82601f830112611c7a575f80fd5b813567ffffffffffffffff811115611c9457611c94611c26565b611ca7601f8201601f1916602001611c3a565b818152846020838601011115611cbb575f80fd5b816020850160208301375f918101602001919091529392505050565b5f60208284031215611ce7575f80fd5b813567ffffffffffffffff811115611cfd575f80fd5b611d0984828501611c6b565b949350505050565b6001600160a01b0381168114611d25575f80fd5b50565b5f60208284031215611d38575f80fd5b8135611c1f81611d11565b5f60208284031215611d53575f80fd5b5035919050565b5f81518084525f5b81811015611d7e57602081850181015186830182015201611d62565b505f602082860101526020601f19601f83011685010191505092915050565b8715158152866020820152851515604082015260e060608201525f611dc560e0830187611d5a565b8281036080840152611dd78187611d5a565b905082810360a0840152611deb8186611d5a565b905082810360c0840152611dff8185611d5a565b9a9950505050505050505050565b602081525f611c1f6020830184611d5a565b5f8060408385031215611e30575f80fd5b50508035926020909101359150565b87151581525f602088602084015260e06040840152611e6160e0840189611d5a565b8381036060850152611e738189611d5a565b90508381036080850152611e878188611d5a565b905083810360a0850152611e9b8187611d5a565b84810360c0860152855180825260208088019350909101905f5b81811015611ed157835183529284019291840191600101611eb5565b50909c9b505050505050505050505050565b5f805f60608486031215611ef5575f80fd5b8335925060208401359150604084013567ffffffffffffffff811115611f19575f80fd5b611f2586828701611c6b565b9150509250925092565b5f8060408385031215611f40575f80fd5b823591506020830135611f5281611d11565b809150509250929050565b8615158152856020820152841515604082015260c060608201525f611f8560c0830186611d5a565b8281036080840152611f978186611d5a565b905082810360a0840152611fab8185611d5a565b9998505050505050505050565b80358015158114611fc7575f80fd5b919050565b5f805f805f805f60e0888a031215611fe2575f80fd5b87359650611ff260208901611fb8565b95506040880135945061200760608901611fb8565b9350608088013567ffffffffffffffff80821115612023575f80fd5b61202f8b838c01611c6b565b945060a08a0135915080821115612044575f80fd5b6120508b838c01611c6b565b935060c08a0135915080821115612065575f80fd5b506120728a828b01611c6b565b91505092959891949750929550565b604081525f6120936040830185611d5a565b90508260208301529392505050565b600181811c908216806120b657607f821691505b6020821081036120d457634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111561212157805f5260205f20601f840160051c810160208510156120ff5750805b601f840160051c820191505b8181101561211e575f815560010161210b565b50505b505050565b815167ffffffffffffffff81111561214057612140611c26565b6121548161214e84546120a2565b846120da565b602080601f831160018114612187575f84156121705750858301515b5f19600386901b1c1916600185901b1785556121de565b5f85815260208120601f198616915b828110156121b557888601518255948401946001909101908401612196565b50858210156121d257878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b5f602082840312156121f6575f80fd5b8151611c1f81611d11565b6020808252600e908201526d139bdd08185d5d1a1bdc9a5e995960921b604082015260600190565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561196e5761196e612229565b634e487b7160e01b5f52603260045260245ffd5b5f6001820161227557612275612229565b5060010190565b5f82601f83011261228b575f80fd5b8151602067ffffffffffffffff8211156122a7576122a7611c26565b8160051b6122b6828201611c3a565b92835284810182019282810190878511156122cf575f80fd5b83870192505b848310156122ee578251825291830191908301906122d5565b979650505050505050565b5f806040838503121561230a575f80fd5b825167ffffffffffffffff80821115612321575f80fd5b61232d8683870161227c565b93506020850151915080821115612342575f80fd5b5061234f8582860161227c565b915050925092905056fea264697066735822122015d0973621d1e015dee86e9dd609ba0f3e922134d7b07ea25d49433b677547dc64736f6c63430008180033
|
{"DungeonConfig.sol":{"content":"// SPDX-License-Identifier: MIT\r\n//\r\n// DungeonConfig by DungeonMaster/@DungeonSpawner\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./Ownable.sol\";\r\n\r\ninterface IDungeon {\r\n function ownerOf(uint256 tokenId) external view returns (address owner);\r\n}\r\n\r\ninterface IDungeonRewards {\r\n function getStakedTokens(\r\n address owner\r\n )\r\n external\r\n view\r\n returns (uint256[] memory dungeons, uint256[] memory avatars);\r\n}\r\n\r\ncontract DungeonConfig is Ownable {\r\n /*///////////////////////////////////////////////////////////////\r\n EVENTS\r\n //////////////////////////////////////////////////////////////*/\r\n event AssignPerms(\r\n address indexed from,\r\n address indexed to,\r\n uint256 indexed tokenId\r\n );\r\n event AssignGlobalPerms(address indexed from, address indexed to);\r\n event RevokeGlobalPerms(address indexed from, address indexed to);\r\n\r\n /*///////////////////////////////////////////////////////////////\r\n METADATA STORAGE/LOGIC\r\n //////////////////////////////////////////////////////////////*/\r\n address public dungeonAddress;\r\n address public dungeonRewardsAddress;\r\n\r\n struct Permission {\r\n address grantedBy; // The address that granted the permission\r\n address grantedTo; // The address that received the permission\r\n }\r\n struct GlobalPermission {\r\n address grantedTo;\r\n address grantedBy;\r\n }\r\n\r\n struct FloorData {\r\n string txId; // transaction ID for the floor data\r\n uint256 version; // current version of the floor data (every resetAllFloors increments the version #, outdating previous entries)\r\n }\r\n\r\n struct DungeonData {\r\n bool locked;\r\n uint256 trialTimeout;\r\n bool randomizeLayout; // randomize layout indicates each floor after floor 1 has a random layout/environment\r\n string passwordHash; // DungeonMaster notes: not really secure, of course, since it\u0027s publically available, but the best we have\r\n string ownersMessage;\r\n string gameMode; // if starts with https:, NFT will redirect here after loading up (use for streaming via rumble, 3D client, etc)\r\n }\r\n\r\n // Mapping that tells us which version of the dungeon data we\u0027re dealing with \r\n // (reseting all floors increments the version # -- saves us gas from having to clear all the existing dungeon floor data)\r\n mapping(uint256 =\u003e uint256) private tokenVersions;\r\n\r\n mapping(uint256 =\u003e DungeonData) public dungeons;\r\n // Mapping from tokenId to a mapping of floorNumber to FloorData\r\n mapping(uint256 =\u003e mapping(uint256 =\u003e FloorData)) public dungeonFloors;\r\n\r\n mapping(uint256 =\u003e Permission) public tokenPermissions;\r\n // Mapping to store global permissions\r\n mapping(address =\u003e GlobalPermission) public globalPermissions;\r\n\r\n string public BASE_CODE_TXID = \"\"; // base code txid\r\n\r\n constructor(address _dungeonAddress, address _dungeonRewardsAddress) {\r\n dungeonAddress = _dungeonAddress;\r\n dungeonRewardsAddress = _dungeonRewardsAddress;\r\n }\r\n\r\n modifier onlyOwnerOrStaker(uint256 tokenId) {\r\n IDungeon dungeon = IDungeon(dungeonAddress);\r\n address owner = dungeon.ownerOf(tokenId);\r\n bool isStaker = owner == dungeonRewardsAddress \u0026\u0026\r\n isTokenStakedByAddress(tokenId, msg.sender);\r\n\r\n require(\r\n owner == msg.sender || isStaker,\r\n \"Caller is not owner or staker\"\r\n );\r\n _;\r\n }\r\n\r\n function isTokenStakedByAddress(\r\n uint256 tokenId,\r\n address addressToCheck\r\n ) private view returns (bool) {\r\n IDungeonRewards rewards = IDungeonRewards(dungeonRewardsAddress);\r\n (uint256[] memory stakedDungeons, ) = rewards.getStakedTokens(\r\n addressToCheck\r\n );\r\n for (uint i = 0; i \u003c stakedDungeons.length; i++) {\r\n if (stakedDungeons[i] == tokenId) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n modifier isPermitted(uint256 tokenId) {\r\n IDungeon dungeon = IDungeon(dungeonAddress);\r\n address owner = dungeon.ownerOf(tokenId);\r\n\r\n // First, check if msg.sender is the owner. If true, no further checks needed.\r\n if (\r\n owner == msg.sender ||\r\n (owner == dungeonRewardsAddress \u0026\u0026\r\n isTokenStakedByAddress(tokenId, msg.sender))\r\n ) {\r\n _;\r\n return;\r\n }\r\n\r\n // Global Permissions Check\r\n GlobalPermission memory globalPerm = globalPermissions[msg.sender];\r\n if (globalPerm.grantedTo == msg.sender) {\r\n bool isGlobalGrantorOwnerOrStaker = globalPerm.grantedBy == owner ||\r\n (owner == dungeonRewardsAddress \u0026\u0026\r\n isTokenStakedByAddress(tokenId, globalPerm.grantedBy));\r\n\r\n if (isGlobalGrantorOwnerOrStaker) {\r\n _;\r\n return;\r\n }\r\n }\r\n\r\n // Only proceed to check permissions if the sender is not the owner or a staker.\r\n Permission memory permission = tokenPermissions[tokenId];\r\n bool hasValidPermission = permission.grantedTo == msg.sender \u0026\u0026\r\n (permission.grantedBy == owner ||\r\n (owner == dungeonRewardsAddress \u0026\u0026\r\n isTokenStakedByAddress(tokenId, permission.grantedBy)));\r\n\r\n require(hasValidPermission, \"Not authorized\");\r\n\r\n _;\r\n }\r\n\r\n function writeDungeonConfig(\r\n uint256 tokenId,\r\n bool locked,\r\n uint256 trialTimeout,\r\n bool randomizeLayout,\r\n string memory passwordHash,\r\n string memory ownersMessage,\r\n string memory gameMode\r\n ) public isPermitted(tokenId) {\r\n DungeonData storage dungeon = dungeons[tokenId];\r\n dungeon.locked = locked;\r\n dungeon.trialTimeout = trialTimeout;\r\n dungeon.randomizeLayout = randomizeLayout;\r\n dungeon.passwordHash = passwordHash;\r\n dungeon.ownersMessage = ownersMessage;\r\n dungeon.gameMode = gameMode;\r\n }\r\n\r\n function readDungeonConfig(\r\n uint256 tokenId\r\n )\r\n public\r\n view\r\n returns (\r\n bool locked,\r\n uint256 trialTimeout,\r\n bool randomizeLayout,\r\n string memory passwordHash,\r\n string memory ownersMessage,\r\n string memory gameMode,\r\n string memory codeTxId\r\n )\r\n {\r\n DungeonData memory dungeon = dungeons[tokenId];\r\n return (\r\n dungeon.locked,\r\n dungeon.trialTimeout,\r\n dungeon.randomizeLayout,\r\n dungeon.passwordHash,\r\n dungeon.ownersMessage,\r\n dungeon.gameMode,\r\n BASE_CODE_TXID\r\n );\r\n }\r\n\r\n // read Dungeon Config with custom floors\r\n function readDungeonConfig(\r\n uint256 tokenId, uint256 maxFloorNumber\r\n )\r\n public\r\n view\r\n returns (\r\n bool locked,\r\n uint256 trialTimeout,\r\n string memory passwordHash,\r\n string memory ownersMessage,\r\n string memory gameMode,\r\n string memory codeTxId,\r\n uint256[] memory customFloors\r\n )\r\n {\r\n DungeonData memory dungeon = dungeons[tokenId];\r\n uint256 currentVersion = tokenVersions[tokenId];\r\n\r\n // Directly use the fields from the dungeon struct to construct the return values\r\n locked = dungeon.locked;\r\n trialTimeout = dungeon.trialTimeout;\r\n passwordHash = dungeon.passwordHash;\r\n ownersMessage = dungeon.ownersMessage;\r\n gameMode = dungeon.gameMode;\r\n codeTxId = BASE_CODE_TXID;\r\n\r\n // Use the helper function to get customFloors - do it this way to avoid CompilerError: Stack too deep\r\n customFloors = getCustomFloors(tokenId, maxFloorNumber, currentVersion);\r\n }\r\n\r\n // collect customFloors data\r\n function getCustomFloors(uint256 tokenId, uint256 maxFloorNumber, uint256 currentVersion)\r\n internal\r\n view\r\n returns (uint256[] memory customFloors)\r\n {\r\n uint256[] memory tempFloors = new uint256[](maxFloorNumber);\r\n uint256 count = 0;\r\n\r\n for (uint256 floor = 0; floor \u003c= maxFloorNumber; floor++) {\r\n if (dungeonFloors[tokenId][floor].version == currentVersion \u0026\u0026\r\n bytes(dungeonFloors[tokenId][floor].txId).length \u003e 0) {\r\n tempFloors[count] = floor;\r\n count++;\r\n }\r\n }\r\n\r\n customFloors = new uint256[](count);\r\n for (uint256 i = 0; i \u003c count; i++) {\r\n customFloors[i] = tempFloors[i];\r\n }\r\n }\r\n\r\n function writeFloorData(\r\n uint256 tokenId,\r\n uint256 floorNumber,\r\n string memory txId\r\n ) public isPermitted(tokenId) {\r\n // Store the transaction ID for the specific floor\r\n dungeonFloors[tokenId][floorNumber] = FloorData(txId, tokenVersions[tokenId]);\r\n }\r\n\r\n function readFloorData(\r\n uint256 tokenId,\r\n uint256 floorNumber\r\n ) public view returns (string memory) {\r\n FloorData memory floorData = dungeonFloors[tokenId][floorNumber];\r\n // Return the transaction ID for the specific floor\r\n if(floorData.version == tokenVersions[tokenId]) {\r\n return floorData.txId;\r\n } else {\r\n return \"\"; // Indicates no data for the current version\r\n } \r\n }\r\n\r\n function resetAllFloors(uint256 tokenId) public isPermitted(tokenId) { \r\n tokenVersions[tokenId] += 1; // Increment the version to \"reset\" the data\r\n }\r\n\r\n function assignPermission(\r\n uint256 tokenId,\r\n address to\r\n ) public onlyOwnerOrStaker(tokenId) {\r\n tokenPermissions[tokenId] = Permission(msg.sender, to);\r\n\r\n emit AssignPerms(msg.sender, to, tokenId);\r\n }\r\n\r\n // Assign global permission\r\n function assignGlobalPermission(address to) public {\r\n globalPermissions[to] = GlobalPermission({\r\n grantedTo: to,\r\n grantedBy: msg.sender\r\n });\r\n\r\n emit AssignGlobalPerms(msg.sender, to);\r\n }\r\n\r\n // Optional: Function to revoke global permission\r\n function revokeGlobalPermission(address to) public {\r\n require(\r\n globalPermissions[to].grantedBy == msg.sender,\r\n \"Not authorized to revoke\"\r\n );\r\n delete globalPermissions[to];\r\n emit RevokeGlobalPerms(msg.sender, to);\r\n }\r\n\r\n // set the ethscription txid of the base codebase\r\n function setBaseCodeTxid(string memory baseCodeTxid) public onlyOwner {\r\n BASE_CODE_TXID = baseCodeTxid;\r\n }\r\n\r\n // read the ethscription txid of the base codebase\r\n function getBaseCodeTxid() public view returns (string memory) {\r\n return BASE_CODE_TXID;\r\n }\r\n\r\n}\r\n"},"Ownable.sol":{"content":"// SPDX-License-Identifier: AGPL-3.0-only\r\npragma solidity ^0.8.10;\r\n\r\nerror NotOwner();\r\n\r\n// https://github.com/m1guelpf/erc721-drop/blob/main/src/LilOwnable.sol\r\nabstract contract Ownable {\r\n address internal _owner;\r\n\r\n event OwnershipTransferred(\r\n address indexed previousOwner,\r\n address indexed newOwner\r\n );\r\n\r\n modifier onlyOwner() {\r\n require(_owner == msg.sender);\r\n _;\r\n }\r\n\r\n constructor() {\r\n _owner = msg.sender;\r\n }\r\n\r\n function owner() external view returns (address) {\r\n return _owner;\r\n }\r\n\r\n function transferOwnership(address _newOwner) external {\r\n if (msg.sender != _owner) revert NotOwner();\r\n\r\n _owner = _newOwner;\r\n }\r\n\r\n function renounceOwnership() public {\r\n if (msg.sender != _owner) revert NotOwner();\r\n\r\n _owner = address(0);\r\n }\r\n\r\n function supportsInterface(bytes4 interfaceId)\r\n public\r\n pure\r\n virtual\r\n returns (bool)\r\n {\r\n return interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173\r\n }\r\n}\r\n"}}
|
1 | 19,499,894 |
26830bbb47785eb47d0ea4489549e4f76cf8edc8369530a4eaf59e0ef3de940c
|
985d17f843715849a42787c34a611061281becd504c5d08c8f52bcc19e346845
|
fc0a22a4883f67156655d497eecd03674bc99296
|
fc0a22a4883f67156655d497eecd03674bc99296
|
0aa81c3002e23fe9fb5083248ed5857834e14492
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f62b1cbc838b27cab7b4b813902e9a526a40fffb0d36007557f6e75382374384e10a7b62f62d4deec44f9ffde0a59bd57064cb9cee22c0b5bd76008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103648061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030b565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b600060208284031215610304578081fd5b5035919050565b60008282101561032957634e487b7160e01b81526011600452602481fd5b50039056fea2646970667358221220618853bdb35994d44a56c8bd229e2167bbd814b3796a1cd89537a2a0d432030a64736f6c63430008040033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030b565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b600060208284031215610304578081fd5b5035919050565b60008282101561032957634e487b7160e01b81526011600452602481fd5b50039056fea2646970667358221220618853bdb35994d44a56c8bd229e2167bbd814b3796a1cd89537a2a0d432030a64736f6c63430008040033
| |
1 | 19,499,899 |
b3313dcddcbcaacbfe0e870c616d83447d7b3634a4027ad702c699f077ce830d
|
bc52d47db662e7013d66041bc493c6d30870fe5648cf5a7e5547bf4b767b1eeb
|
f2d98377d80dadf725bfb97e91357f1d81384de2
|
90eb22a31b69c29c34162e0e9278cc0617aa2b50
|
c510caa5c7a4c23707d201f7a91f59ad0781d7d6
|
3d602d80600a3d3981f3363d3d373d3d3d363d734edeb80ce684a890dd58ae0d9762c38731b11b995af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d734edeb80ce684a890dd58ae0d9762c38731b11b995af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n function decimals() external view returns (uint8);\n\n function description() external view returns (string memory);\n\n function version() external view returns (uint256);\n\n function getRoundData(uint80 _roundId)\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n}\n"
},
"@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControlUpgradeable {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"contracts/interfaces/IAsset.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"../libraries/Fixed.sol\";\nimport \"./IMain.sol\";\nimport \"./IRewardable.sol\";\n\n// Not used directly in the IAsset interface, but used by many consumers to save stack space\nstruct Price {\n uint192 low; // {UoA/tok}\n uint192 high; // {UoA/tok}\n}\n\n/**\n * @title IAsset\n * @notice Supertype. Any token that interacts with our system must be wrapped in an asset,\n * whether it is used as RToken backing or not. Any token that can report a price in the UoA\n * is eligible to be an asset.\n */\ninterface IAsset is IRewardable {\n /// Refresh saved price\n /// The Reserve protocol calls this at least once per transaction, before relying on\n /// the Asset's other functions.\n /// @dev Called immediately after deployment, before use\n function refresh() external;\n\n /// Should not revert\n /// low should be nonzero if the asset could be worth selling\n /// @return low {UoA/tok} The lower end of the price estimate\n /// @return high {UoA/tok} The upper end of the price estimate\n function price() external view returns (uint192 low, uint192 high);\n\n /// Should not revert\n /// lotLow should be nonzero when the asset might be worth selling\n /// @dev Deprecated. Phased out in 3.1.0, but left on interface for backwards compatibility\n /// @return lotLow {UoA/tok} The lower end of the lot price estimate\n /// @return lotHigh {UoA/tok} The upper end of the lot price estimate\n function lotPrice() external view returns (uint192 lotLow, uint192 lotHigh);\n\n /// @return {tok} The balance of the ERC20 in whole tokens\n function bal(address account) external view returns (uint192);\n\n /// @return The ERC20 contract of the token with decimals() available\n function erc20() external view returns (IERC20Metadata);\n\n /// @return The number of decimals in the ERC20; just for gas optimization\n function erc20Decimals() external view returns (uint8);\n\n /// @return If the asset is an instance of ICollateral or not\n function isCollateral() external view returns (bool);\n\n /// @return {UoA} The max trade volume, in UoA\n function maxTradeVolume() external view returns (uint192);\n\n /// @return {s} The timestamp of the last refresh() that saved prices\n function lastSave() external view returns (uint48);\n}\n\n// Used only in Testing. Strictly speaking an Asset does not need to adhere to this interface\ninterface TestIAsset is IAsset {\n /// @return The address of the chainlink feed\n function chainlinkFeed() external view returns (AggregatorV3Interface);\n\n /// {1} The max % deviation allowed by the oracle\n function oracleError() external view returns (uint192);\n\n /// @return {s} Seconds that an oracle value is considered valid\n function oracleTimeout() external view returns (uint48);\n\n /// @return {s} The maximum of all oracle timeouts on the plugin\n function maxOracleTimeout() external view returns (uint48);\n\n /// @return {s} Seconds that the price() should decay over, after stale price\n function priceTimeout() external view returns (uint48);\n\n /// @return {UoA/tok} The last saved low price\n function savedLowPrice() external view returns (uint192);\n\n /// @return {UoA/tok} The last saved high price\n function savedHighPrice() external view returns (uint192);\n}\n\n/// CollateralStatus must obey a linear ordering. That is:\n/// - being DISABLED is worse than being IFFY, or SOUND\n/// - being IFFY is worse than being SOUND.\nenum CollateralStatus {\n SOUND,\n IFFY, // When a peg is not holding or a chainlink feed is stale\n DISABLED // When the collateral has completely defaulted\n}\n\n/// Upgrade-safe maximum operator for CollateralStatus\nlibrary CollateralStatusComparator {\n /// @return Whether a is worse than b\n function worseThan(CollateralStatus a, CollateralStatus b) internal pure returns (bool) {\n return uint256(a) > uint256(b);\n }\n}\n\n/**\n * @title ICollateral\n * @notice A subtype of Asset that consists of the tokens eligible to back the RToken.\n */\ninterface ICollateral is IAsset {\n /// Emitted whenever the collateral status is changed\n /// @param newStatus The old CollateralStatus\n /// @param newStatus The updated CollateralStatus\n event CollateralStatusChanged(\n CollateralStatus indexed oldStatus,\n CollateralStatus indexed newStatus\n );\n\n /// @dev refresh()\n /// Refresh exchange rates and update default status.\n /// VERY IMPORTANT: In any valid implemntation, status() MUST become DISABLED in refresh() if\n /// refPerTok() has ever decreased since last call.\n\n /// @return The canonical name of this collateral's target unit.\n function targetName() external view returns (bytes32);\n\n /// @return The status of this collateral asset. (Is it defaulting? Might it soon?)\n function status() external view returns (CollateralStatus);\n\n // ==== Exchange Rates ====\n\n /// @return {ref/tok} Quantity of whole reference units per whole collateral tokens\n function refPerTok() external view returns (uint192);\n\n /// @return {target/ref} Quantity of whole target units per whole reference unit in the peg\n function targetPerRef() external view returns (uint192);\n}\n\n// Used only in Testing. Strictly speaking a Collateral does not need to adhere to this interface\ninterface TestICollateral is TestIAsset, ICollateral {\n /// @return The epoch timestamp when the collateral will default from IFFY to DISABLED\n function whenDefault() external view returns (uint256);\n\n /// @return The amount of time a collateral must be in IFFY status until being DISABLED\n function delayUntilDefault() external view returns (uint48);\n\n /// @return The underlying refPerTok, likely not included in all collaterals however.\n function underlyingRefPerTok() external view returns (uint192);\n}\n"
},
"contracts/interfaces/IAssetRegistry.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IAsset.sol\";\nimport \"./IComponent.sol\";\n\n/// A serialization of the AssetRegistry to be passed around in the P1 impl for gas optimization\nstruct Registry {\n IERC20[] erc20s;\n IAsset[] assets;\n}\n\n/**\n * @title IAssetRegistry\n * @notice The AssetRegistry is in charge of maintaining the ERC20 tokens eligible\n * to be handled by the rest of the system. If an asset is in the registry, this means:\n * 1. Its ERC20 contract has been vetted\n * 2. The asset is the only asset for that ERC20\n * 3. The asset can be priced in the UoA, usually via an oracle\n */\ninterface IAssetRegistry is IComponent {\n /// Emitted when an asset is added to the registry\n /// @param erc20 The ERC20 contract for the asset\n /// @param asset The asset contract added to the registry\n event AssetRegistered(IERC20 indexed erc20, IAsset indexed asset);\n\n /// Emitted when an asset is removed from the registry\n /// @param erc20 The ERC20 contract for the asset\n /// @param asset The asset contract removed from the registry\n event AssetUnregistered(IERC20 indexed erc20, IAsset indexed asset);\n\n // Initialization\n function init(IMain main_, IAsset[] memory assets_) external;\n\n /// Fully refresh all asset state\n /// @custom:refresher\n function refresh() external;\n\n /// Register `asset`\n /// If either the erc20 address or the asset was already registered, fail\n /// @return true if the erc20 address was not already registered.\n /// @custom:governance\n function register(IAsset asset) external returns (bool);\n\n /// Register `asset` if and only if its erc20 address is already registered.\n /// If the erc20 address was not registered, revert.\n /// @return swapped If the asset was swapped for a previously-registered asset\n /// @custom:governance\n function swapRegistered(IAsset asset) external returns (bool swapped);\n\n /// Unregister an asset, requiring that it is already registered\n /// @custom:governance\n function unregister(IAsset asset) external;\n\n /// @return {s} The timestamp of the last refresh\n function lastRefresh() external view returns (uint48);\n\n /// @return The corresponding asset for ERC20, or reverts if not registered\n function toAsset(IERC20 erc20) external view returns (IAsset);\n\n /// @return The corresponding collateral, or reverts if unregistered or not collateral\n function toColl(IERC20 erc20) external view returns (ICollateral);\n\n /// @return If the ERC20 is registered\n function isRegistered(IERC20 erc20) external view returns (bool);\n\n /// @return A list of all registered ERC20s\n function erc20s() external view returns (IERC20[] memory);\n\n /// @return reg The list of registered ERC20s and Assets, in the same order\n function getRegistry() external view returns (Registry memory reg);\n\n /// @return The number of registered ERC20s\n function size() external view returns (uint256);\n}\n"
},
"contracts/interfaces/IBackingManager.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IAssetRegistry.sol\";\nimport \"./IBasketHandler.sol\";\nimport \"./IBroker.sol\";\nimport \"./IComponent.sol\";\nimport \"./IRToken.sol\";\nimport \"./IStRSR.sol\";\nimport \"./ITrading.sol\";\n\n/// Memory struct for RecollateralizationLibP1 + RTokenAsset\n/// Struct purposes:\n/// 1. Configure trading\n/// 2. Stay under stack limit with fewer vars\n/// 3. Cache information such as component addresses and basket quantities, to save on gas\nstruct TradingContext {\n BasketRange basketsHeld; // {BU}\n // basketsHeld.top is the number of partial baskets units held\n // basketsHeld.bottom is the number of full basket units held\n\n // Components\n IBasketHandler bh;\n IAssetRegistry ar;\n IStRSR stRSR;\n IERC20 rsr;\n IRToken rToken;\n // Gov Vars\n uint192 minTradeVolume; // {UoA}\n uint192 maxTradeSlippage; // {1}\n // Cached values\n uint192[] quantities; // {tok/BU} basket quantities\n uint192[] bals; // {tok} balances in BackingManager + out on trades\n}\n\n/**\n * @title IBackingManager\n * @notice The BackingManager handles changes in the ERC20 balances that back an RToken.\n * - It computes which trades to perform, if any, and initiates these trades with the Broker.\n * - rebalance()\n * - If already collateralized, excess assets are transferred to RevenueTraders.\n * - forwardRevenue(IERC20[] calldata erc20s)\n */\ninterface IBackingManager is IComponent, ITrading {\n /// Emitted when the trading delay is changed\n /// @param oldVal The old trading delay\n /// @param newVal The new trading delay\n event TradingDelaySet(uint48 oldVal, uint48 newVal);\n\n /// Emitted when the backing buffer is changed\n /// @param oldVal The old backing buffer\n /// @param newVal The new backing buffer\n event BackingBufferSet(uint192 oldVal, uint192 newVal);\n\n // Initialization\n function init(\n IMain main_,\n uint48 tradingDelay_,\n uint192 backingBuffer_,\n uint192 maxTradeSlippage_,\n uint192 minTradeVolume_\n ) external;\n\n // Give RToken max allowance over a registered token\n /// @custom:refresher\n /// @custom:interaction\n function grantRTokenAllowance(IERC20) external;\n\n /// Apply the overall backing policy using the specified TradeKind, taking a haircut if unable\n /// @param kind TradeKind.DUTCH_AUCTION or TradeKind.BATCH_AUCTION\n /// @custom:interaction RCEI\n function rebalance(TradeKind kind) external;\n\n /// Forward revenue to RevenueTraders; reverts if not fully collateralized\n /// @param erc20s The tokens to forward\n /// @custom:interaction RCEI\n function forwardRevenue(IERC20[] calldata erc20s) external;\n\n /// Structs for trading\n /// @param basketsHeld The number of baskets held by the BackingManager\n /// @return ctx The TradingContext\n /// @return reg Contents of AssetRegistry.getRegistry()\n function tradingContext(BasketRange memory basketsHeld)\n external\n view\n returns (TradingContext memory ctx, Registry memory reg);\n}\n\ninterface TestIBackingManager is IBackingManager, TestITrading {\n function tradingDelay() external view returns (uint48);\n\n function backingBuffer() external view returns (uint192);\n\n function setTradingDelay(uint48 val) external;\n\n function setBackingBuffer(uint192 val) external;\n}\n"
},
"contracts/interfaces/IBasketHandler.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../libraries/Fixed.sol\";\nimport \"./IAsset.sol\";\nimport \"./IComponent.sol\";\n\nstruct BasketRange {\n uint192 bottom; // {BU}\n uint192 top; // {BU}\n}\n\n/**\n * @title IBasketHandler\n * @notice The BasketHandler aims to maintain a reference basket of constant target unit amounts.\n * When a collateral token defaults, a new reference basket of equal target units is set.\n * When _all_ collateral tokens default for a target unit, only then is the basket allowed to fall\n * in terms of target unit amounts. The basket is considered defaulted in this case.\n */\ninterface IBasketHandler is IComponent {\n /// Emitted when the prime basket is set\n /// @param erc20s The collateral tokens for the prime basket\n /// @param targetAmts {target/BU} A list of quantities of target unit per basket unit\n /// @param targetNames Each collateral token's targetName\n event PrimeBasketSet(IERC20[] erc20s, uint192[] targetAmts, bytes32[] targetNames);\n\n /// Emitted when the reference basket is set\n /// @param nonce {basketNonce} The basket nonce\n /// @param erc20s The list of collateral tokens in the reference basket\n /// @param refAmts {ref/BU} The reference amounts of the basket collateral tokens\n /// @param disabled True when the list of erc20s + refAmts may not be correct\n event BasketSet(uint256 indexed nonce, IERC20[] erc20s, uint192[] refAmts, bool disabled);\n\n /// Emitted when a backup config is set for a target unit\n /// @param targetName The name of the target unit as a bytes32\n /// @param max The max number to use from `erc20s`\n /// @param erc20s The set of backup collateral tokens\n event BackupConfigSet(bytes32 indexed targetName, uint256 max, IERC20[] erc20s);\n\n /// Emitted when the warmup period is changed\n /// @param oldVal The old warmup period\n /// @param newVal The new warmup period\n event WarmupPeriodSet(uint48 oldVal, uint48 newVal);\n\n /// Emitted when the status of a basket has changed\n /// @param oldStatus The previous basket status\n /// @param newStatus The new basket status\n event BasketStatusChanged(CollateralStatus oldStatus, CollateralStatus newStatus);\n\n /// Emitted when the last basket nonce available for redemption is changed\n /// @param oldVal The old value of lastCollateralized\n /// @param newVal The new value of lastCollateralized\n event LastCollateralizedChanged(uint48 oldVal, uint48 newVal);\n\n // Initialization\n function init(\n IMain main_,\n uint48 warmupPeriod_,\n bool reweightable_\n ) external;\n\n /// Set the prime basket\n /// For an index RToken (reweightable = true), use forceSetPrimeBasket to skip normalization\n /// @param erc20s The collateral tokens for the new prime basket\n /// @param targetAmts The target amounts (in) {target/BU} for the new prime basket\n /// required range: 1e9 values; absolute range irrelevant.\n /// @custom:governance\n function setPrimeBasket(IERC20[] calldata erc20s, uint192[] calldata targetAmts) external;\n\n /// Set the prime basket without normalizing targetAmts by the UoA of the current basket\n /// Works the same as setPrimeBasket for non-index RTokens (reweightable = false)\n /// @param erc20s The collateral tokens for the new prime basket\n /// @param targetAmts The target amounts (in) {target/BU} for the new prime basket\n /// required range: 1e9 values; absolute range irrelevant.\n /// @custom:governance\n function forceSetPrimeBasket(IERC20[] calldata erc20s, uint192[] calldata targetAmts) external;\n\n /// Set the backup configuration for a given target\n /// @param targetName The name of the target as a bytes32\n /// @param max The maximum number of collateral tokens to use from this target\n /// Required range: 1-255\n /// @param erc20s A list of ordered backup collateral tokens\n /// @custom:governance\n function setBackupConfig(\n bytes32 targetName,\n uint256 max,\n IERC20[] calldata erc20s\n ) external;\n\n /// Default the basket in order to schedule a basket refresh\n /// @custom:protected\n function disableBasket() external;\n\n /// Governance-controlled setter to cause a basket switch explicitly\n /// @custom:governance\n /// @custom:interaction\n function refreshBasket() external;\n\n /// Track the basket status changes\n /// @custom:refresher\n function trackStatus() external;\n\n /// Track when last collateralized\n /// @custom:refresher\n function trackCollateralization() external;\n\n /// @return If the BackingManager has sufficient collateral to redeem the entire RToken supply\n function fullyCollateralized() external view returns (bool);\n\n /// @return status The worst CollateralStatus of all collateral in the basket\n function status() external view returns (CollateralStatus status);\n\n /// @return If the basket is ready to issue and trade\n function isReady() external view returns (bool);\n\n /// @param erc20 The ERC20 token contract for the asset\n /// @return {tok/BU} The whole token quantity of token in the reference basket\n /// Returns 0 if erc20 is not registered or not in the basket\n /// Returns FIX_MAX (in lieu of +infinity) if Collateral.refPerTok() is 0.\n /// Otherwise, returns (token's basket.refAmts / token's Collateral.refPerTok())\n function quantity(IERC20 erc20) external view returns (uint192);\n\n /// Like quantity(), but unsafe because it DOES NOT CONFIRM THAT THE ASSET IS CORRECT\n /// @param erc20 The ERC20 token contract for the asset\n /// @param asset The registered asset plugin contract for the erc20\n /// @return {tok/BU} The whole token quantity of token in the reference basket\n /// Returns 0 if erc20 is not registered or not in the basket\n /// Returns FIX_MAX (in lieu of +infinity) if Collateral.refPerTok() is 0.\n /// Otherwise, returns (token's basket.refAmts / token's Collateral.refPerTok())\n function quantityUnsafe(IERC20 erc20, IAsset asset) external view returns (uint192);\n\n /// @param amount {BU}\n /// @return erc20s The addresses of the ERC20 tokens in the reference basket\n /// @return quantities {qTok} The quantity of each ERC20 token to issue `amount` baskets\n function quote(uint192 amount, RoundingMode rounding)\n external\n view\n returns (address[] memory erc20s, uint256[] memory quantities);\n\n /// Return the redemption value of `amount` BUs for a linear combination of historical baskets\n /// @param basketNonces An array of basket nonces to do redemption from\n /// @param portions {1} An array of Fix quantities that must add up to FIX_ONE\n /// @param amount {BU}\n /// @return erc20s The backing collateral erc20s\n /// @return quantities {qTok} ERC20 token quantities equal to `amount` BUs\n function quoteCustomRedemption(\n uint48[] memory basketNonces,\n uint192[] memory portions,\n uint192 amount\n ) external view returns (address[] memory erc20s, uint256[] memory quantities);\n\n /// @return top {BU} The number of partial basket units: e.g max(coll.map((c) => c.balAsBUs())\n /// bottom {BU} The number of whole basket units held by the account\n function basketsHeldBy(address account) external view returns (BasketRange memory);\n\n /// Should not revert\n /// low should be nonzero when BUs are worth selling\n /// @return low {UoA/BU} The lower end of the price estimate\n /// @return high {UoA/BU} The upper end of the price estimate\n function price() external view returns (uint192 low, uint192 high);\n\n /// Should not revert\n /// lotLow should be nonzero if a BU could be worth selling\n /// @dev Deprecated. Phased out in 3.1.0, but left on interface for backwards compatibility\n /// @return lotLow {UoA/tok} The lower end of the lot price estimate\n /// @return lotHigh {UoA/tok} The upper end of the lot price estimate\n function lotPrice() external view returns (uint192 lotLow, uint192 lotHigh);\n\n /// @return timestamp The timestamp at which the basket was last set\n function timestamp() external view returns (uint48);\n\n /// @return The current basket nonce, regardless of status\n function nonce() external view returns (uint48);\n}\n\ninterface TestIBasketHandler is IBasketHandler {\n function warmupPeriod() external view returns (uint48);\n\n function setWarmupPeriod(uint48 val) external;\n}\n"
},
"contracts/interfaces/IBroker.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"./IAsset.sol\";\nimport \"./IComponent.sol\";\nimport \"./IGnosis.sol\";\nimport \"./ITrade.sol\";\n\nenum TradeKind {\n DUTCH_AUCTION,\n BATCH_AUCTION\n}\n\n/// Cache of all prices for a pair to prevent re-lookup\nstruct TradePrices {\n uint192 sellLow; // {UoA/sellTok} can be 0\n uint192 sellHigh; // {UoA/sellTok} should not be 0\n uint192 buyLow; // {UoA/buyTok} should not be 0\n uint192 buyHigh; // {UoA/buyTok} should not be 0 or FIX_MAX\n}\n\n/// The data format that describes a request for trade with the Broker\nstruct TradeRequest {\n IAsset sell;\n IAsset buy;\n uint256 sellAmount; // {qSellTok}\n uint256 minBuyAmount; // {qBuyTok}\n}\n\n/**\n * @title IBroker\n * @notice The Broker deploys oneshot Trade contracts for Traders and monitors\n * the continued proper functioning of trading platforms.\n */\ninterface IBroker is IComponent {\n event GnosisSet(IGnosis oldVal, IGnosis newVal);\n event BatchTradeImplementationSet(ITrade oldVal, ITrade newVal);\n event DutchTradeImplementationSet(ITrade oldVal, ITrade newVal);\n event BatchAuctionLengthSet(uint48 oldVal, uint48 newVal);\n event DutchAuctionLengthSet(uint48 oldVal, uint48 newVal);\n event BatchTradeDisabledSet(bool prevVal, bool newVal);\n event DutchTradeDisabledSet(IERC20Metadata indexed erc20, bool prevVal, bool newVal);\n\n // Initialization\n function init(\n IMain main_,\n IGnosis gnosis_,\n ITrade batchTradeImplemention_,\n uint48 batchAuctionLength_,\n ITrade dutchTradeImplemention_,\n uint48 dutchAuctionLength_\n ) external;\n\n /// Request a trade from the broker\n /// @dev Requires setting an allowance in advance\n /// @custom:interaction\n function openTrade(\n TradeKind kind,\n TradeRequest memory req,\n TradePrices memory prices\n ) external returns (ITrade);\n\n /// Only callable by one of the trading contracts the broker deploys\n function reportViolation() external;\n\n function batchTradeDisabled() external view returns (bool);\n\n function dutchTradeDisabled(IERC20Metadata erc20) external view returns (bool);\n}\n\ninterface TestIBroker is IBroker {\n function gnosis() external view returns (IGnosis);\n\n function batchTradeImplementation() external view returns (ITrade);\n\n function dutchTradeImplementation() external view returns (ITrade);\n\n function batchAuctionLength() external view returns (uint48);\n\n function dutchAuctionLength() external view returns (uint48);\n\n function setGnosis(IGnosis newGnosis) external;\n\n function setBatchTradeImplementation(ITrade newTradeImplementation) external;\n\n function setBatchAuctionLength(uint48 newAuctionLength) external;\n\n function setDutchTradeImplementation(ITrade newTradeImplementation) external;\n\n function setDutchAuctionLength(uint48 newAuctionLength) external;\n\n function enableBatchTrade() external;\n\n function enableDutchTrade(IERC20Metadata erc20) external;\n\n // only present on pre-3.0.0 Brokers; used by EasyAuction regression test\n function disabled() external view returns (bool);\n}\n"
},
"contracts/interfaces/IComponent.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"./IMain.sol\";\nimport \"./IVersioned.sol\";\n\n/**\n * @title IComponent\n * @notice A Component is the central building block of all our system contracts. Components\n * contain important state that must be migrated during upgrades, and they delegate\n * their ownership to Main's owner.\n */\ninterface IComponent is IVersioned {\n function main() external view returns (IMain);\n}\n"
},
"contracts/interfaces/IDistributor.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IComponent.sol\";\n\nuint256 constant MAX_DISTRIBUTION = 1e4; // 10,000\nuint8 constant MAX_DESTINATIONS = 100; // maximum number of RevenueShare destinations\n\nstruct RevenueShare {\n uint16 rTokenDist; // {revShare} A value between [0, 10,000]\n uint16 rsrDist; // {revShare} A value between [0, 10,000]\n}\n\n/// Assumes no more than 100 independent distributions.\nstruct RevenueTotals {\n uint24 rTokenTotal; // {revShare}\n uint24 rsrTotal; // {revShare}\n}\n\n/**\n * @title IDistributor\n * @notice The Distributor Component maintains a revenue distribution table that dictates\n * how to divide revenue across the Furnace, StRSR, and any other destinations.\n */\ninterface IDistributor is IComponent {\n /// Emitted when a distribution is set\n /// @param dest The address set to receive the distribution\n /// @param rTokenDist The distribution of RToken that should go to `dest`\n /// @param rsrDist The distribution of RSR that should go to `dest`\n event DistributionSet(address indexed dest, uint16 rTokenDist, uint16 rsrDist);\n\n /// Emitted when revenue is distributed\n /// @param erc20 The token being distributed, either RSR or the RToken itself\n /// @param source The address providing the revenue\n /// @param amount The amount of the revenue\n event RevenueDistributed(IERC20 indexed erc20, address indexed source, uint256 amount);\n\n // Initialization\n function init(IMain main_, RevenueShare memory dist) external;\n\n /// @custom:governance\n function setDistribution(address dest, RevenueShare memory share) external;\n\n /// Distribute the `erc20` token across all revenue destinations\n /// Only callable by RevenueTraders\n /// @custom:protected\n function distribute(IERC20 erc20, uint256 amount) external;\n\n /// @return revTotals The total of all destinations\n function totals() external view returns (RevenueTotals memory revTotals);\n}\n\ninterface TestIDistributor is IDistributor {\n // solhint-disable-next-line func-name-mixedcase\n function FURNACE() external view returns (address);\n\n // solhint-disable-next-line func-name-mixedcase\n function ST_RSR() external view returns (address);\n\n /// @return rTokenDist The RToken distribution for the address\n /// @return rsrDist The RSR distribution for the address\n function distribution(address) external view returns (uint16 rTokenDist, uint16 rsrDist);\n}\n"
},
"contracts/interfaces/IFurnace.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"../libraries/Fixed.sol\";\nimport \"./IComponent.sol\";\n\n/**\n * @title IFurnace\n * @notice A helper contract to burn RTokens slowly and permisionlessly.\n */\ninterface IFurnace is IComponent {\n // Initialization\n function init(IMain main_, uint192 ratio_) external;\n\n /// Emitted when the melting ratio is changed\n /// @param oldRatio The old ratio\n /// @param newRatio The new ratio\n event RatioSet(uint192 oldRatio, uint192 newRatio);\n\n function ratio() external view returns (uint192);\n\n /// Needed value range: [0, 1], granularity 1e-9\n /// @custom:governance\n function setRatio(uint192) external;\n\n /// Performs any RToken melting that has vested since the last payout.\n /// @custom:refresher\n function melt() external;\n}\n\ninterface TestIFurnace is IFurnace {\n function lastPayout() external view returns (uint256);\n\n function lastPayoutBal() external view returns (uint256);\n}\n"
},
"contracts/interfaces/IGnosis.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nstruct GnosisAuctionData {\n IERC20 auctioningToken;\n IERC20 biddingToken;\n uint256 orderCancellationEndDate;\n uint256 auctionEndDate;\n bytes32 initialAuctionOrder;\n uint256 minimumBiddingAmountPerOrder;\n uint256 interimSumBidAmount;\n bytes32 interimOrder;\n bytes32 clearingPriceOrder;\n uint96 volumeClearingPriceOrder;\n bool minFundingThresholdNotReached;\n bool isAtomicClosureAllowed;\n uint256 feeNumerator;\n uint256 minFundingThreshold;\n}\n\n/// The relevant portion of the interface of the live Gnosis EasyAuction contract\n/// https://github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol\ninterface IGnosis {\n function initiateAuction(\n IERC20 auctioningToken,\n IERC20 biddingToken,\n uint256 orderCancellationEndDate,\n uint256 auctionEndDate,\n uint96 auctionedSellAmount,\n uint96 minBuyAmount,\n uint256 minimumBiddingAmountPerOrder,\n uint256 minFundingThreshold,\n bool isAtomicClosureAllowed,\n address accessManagerContract,\n bytes memory accessManagerContractData\n ) external returns (uint256 auctionId);\n\n function auctionData(uint256 auctionId) external view returns (GnosisAuctionData memory);\n\n /// @param auctionId The external auction id\n /// @dev See here for decoding: https://git.io/JMang\n /// @return encodedOrder The order, encoded in a bytes 32\n function settleAuction(uint256 auctionId) external returns (bytes32 encodedOrder);\n\n /// @return The numerator over a 1000-valued denominator\n function feeNumerator() external returns (uint256);\n}\n"
},
"contracts/interfaces/IMain.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IAssetRegistry.sol\";\nimport \"./IBasketHandler.sol\";\nimport \"./IBackingManager.sol\";\nimport \"./IBroker.sol\";\nimport \"./IGnosis.sol\";\nimport \"./IFurnace.sol\";\nimport \"./IDistributor.sol\";\nimport \"./IRToken.sol\";\nimport \"./IRevenueTrader.sol\";\nimport \"./IStRSR.sol\";\nimport \"./ITrading.sol\";\nimport \"./IVersioned.sol\";\n\n// === Auth roles ===\n\nbytes32 constant OWNER = bytes32(bytes(\"OWNER\"));\nbytes32 constant SHORT_FREEZER = bytes32(bytes(\"SHORT_FREEZER\"));\nbytes32 constant LONG_FREEZER = bytes32(bytes(\"LONG_FREEZER\"));\nbytes32 constant PAUSER = bytes32(bytes(\"PAUSER\"));\n\n/**\n * Main is a central hub that maintains a list of Component contracts.\n *\n * Components:\n * - perform a specific function\n * - defer auth to Main\n * - usually (but not always) contain sizeable state that require a proxy\n */\nstruct Components {\n // Definitely need proxy\n IRToken rToken;\n IStRSR stRSR;\n IAssetRegistry assetRegistry;\n IBasketHandler basketHandler;\n IBackingManager backingManager;\n IDistributor distributor;\n IFurnace furnace;\n IBroker broker;\n IRevenueTrader rsrTrader;\n IRevenueTrader rTokenTrader;\n}\n\ninterface IAuth is IAccessControlUpgradeable {\n /// Emitted when `unfreezeAt` is changed\n /// @param oldVal The old value of `unfreezeAt`\n /// @param newVal The new value of `unfreezeAt`\n event UnfreezeAtSet(uint48 oldVal, uint48 newVal);\n\n /// Emitted when the short freeze duration governance param is changed\n /// @param oldDuration The old short freeze duration\n /// @param newDuration The new short freeze duration\n event ShortFreezeDurationSet(uint48 oldDuration, uint48 newDuration);\n\n /// Emitted when the long freeze duration governance param is changed\n /// @param oldDuration The old long freeze duration\n /// @param newDuration The new long freeze duration\n event LongFreezeDurationSet(uint48 oldDuration, uint48 newDuration);\n\n /// Emitted when the system is paused or unpaused for trading\n /// @param oldVal The old value of `tradingPaused`\n /// @param newVal The new value of `tradingPaused`\n event TradingPausedSet(bool oldVal, bool newVal);\n\n /// Emitted when the system is paused or unpaused for issuance\n /// @param oldVal The old value of `issuancePaused`\n /// @param newVal The new value of `issuancePaused`\n event IssuancePausedSet(bool oldVal, bool newVal);\n\n /**\n * Trading Paused: Disable everything except for OWNER actions, RToken.issue, RToken.redeem,\n * StRSR.stake, and StRSR.payoutRewards\n * Issuance Paused: Disable RToken.issue\n * Frozen: Disable everything except for OWNER actions + StRSR.stake (for governance)\n */\n\n function tradingPausedOrFrozen() external view returns (bool);\n\n function issuancePausedOrFrozen() external view returns (bool);\n\n function frozen() external view returns (bool);\n\n function shortFreeze() external view returns (uint48);\n\n function longFreeze() external view returns (uint48);\n\n // ====\n\n // onlyRole(OWNER)\n function freezeForever() external;\n\n // onlyRole(SHORT_FREEZER)\n function freezeShort() external;\n\n // onlyRole(LONG_FREEZER)\n function freezeLong() external;\n\n // onlyRole(OWNER)\n function unfreeze() external;\n\n function pauseTrading() external;\n\n function unpauseTrading() external;\n\n function pauseIssuance() external;\n\n function unpauseIssuance() external;\n}\n\ninterface IComponentRegistry {\n // === Component setters/getters ===\n\n event RTokenSet(IRToken indexed oldVal, IRToken indexed newVal);\n\n function rToken() external view returns (IRToken);\n\n event StRSRSet(IStRSR oldVal, IStRSR newVal);\n\n function stRSR() external view returns (IStRSR);\n\n event AssetRegistrySet(IAssetRegistry oldVal, IAssetRegistry newVal);\n\n function assetRegistry() external view returns (IAssetRegistry);\n\n event BasketHandlerSet(IBasketHandler oldVal, IBasketHandler newVal);\n\n function basketHandler() external view returns (IBasketHandler);\n\n event BackingManagerSet(IBackingManager oldVal, IBackingManager newVal);\n\n function backingManager() external view returns (IBackingManager);\n\n event DistributorSet(IDistributor oldVal, IDistributor newVal);\n\n function distributor() external view returns (IDistributor);\n\n event RSRTraderSet(IRevenueTrader oldVal, IRevenueTrader newVal);\n\n function rsrTrader() external view returns (IRevenueTrader);\n\n event RTokenTraderSet(IRevenueTrader oldVal, IRevenueTrader newVal);\n\n function rTokenTrader() external view returns (IRevenueTrader);\n\n event FurnaceSet(IFurnace oldVal, IFurnace newVal);\n\n function furnace() external view returns (IFurnace);\n\n event BrokerSet(IBroker oldVal, IBroker newVal);\n\n function broker() external view returns (IBroker);\n}\n\n/**\n * @title IMain\n * @notice The central hub for the entire system. Maintains components and an owner singleton role\n */\ninterface IMain is IVersioned, IAuth, IComponentRegistry {\n function poke() external; // not used in p1\n\n // === Initialization ===\n\n event MainInitialized();\n\n function init(\n Components memory components,\n IERC20 rsr_,\n uint48 shortFreeze_,\n uint48 longFreeze_\n ) external;\n\n function rsr() external view returns (IERC20);\n}\n\ninterface TestIMain is IMain {\n /// @custom:governance\n function setShortFreeze(uint48) external;\n\n /// @custom:governance\n function setLongFreeze(uint48) external;\n\n function shortFreeze() external view returns (uint48);\n\n function longFreeze() external view returns (uint48);\n\n function longFreezes(address account) external view returns (uint256);\n\n function tradingPaused() external view returns (bool);\n\n function issuancePaused() external view returns (bool);\n}\n"
},
"contracts/interfaces/IRevenueTrader.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"./IBroker.sol\";\nimport \"./IComponent.sol\";\nimport \"./ITrading.sol\";\n\n/**\n * @title IRevenueTrader\n * @notice The RevenueTrader is an extension of the trading mixin that trades all\n * assets at its address for a single target asset. There are two runtime instances\n * of the RevenueTrader, 1 for RToken and 1 for RSR.\n */\ninterface IRevenueTrader is IComponent, ITrading {\n // Initialization\n function init(\n IMain main_,\n IERC20 tokenToBuy_,\n uint192 maxTradeSlippage_,\n uint192 minTradeVolume_\n ) external;\n\n /// Distribute tokenToBuy to its destinations\n /// @dev Special-case of manageTokens()\n /// @custom:interaction\n function distributeTokenToBuy() external;\n\n /// Return registered ERC20s to the BackingManager if distribution for tokenToBuy is 0\n /// @custom:interaction\n function returnTokens(IERC20[] memory erc20s) external;\n\n /// Process some number of tokens\n /// If the tokenToBuy is included in erc20s, RevenueTrader will distribute it at end of the tx\n /// @param erc20s The ERC20s to manage; can be tokenToBuy or anything registered\n /// @param kinds The kinds of auctions to launch: DUTCH_AUCTION | BATCH_AUCTION\n /// @custom:interaction\n function manageTokens(IERC20[] memory erc20s, TradeKind[] memory kinds) external;\n\n function tokenToBuy() external view returns (IERC20);\n}\n\n// solhint-disable-next-line no-empty-blocks\ninterface TestIRevenueTrader is IRevenueTrader, TestITrading {\n\n}\n"
},
"contracts/interfaces/IRewardable.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IComponent.sol\";\nimport \"./IMain.sol\";\n\n/**\n * @title IRewardable\n * @notice A simple interface mixin to support claiming of rewards.\n */\ninterface IRewardable {\n /// Emitted whenever a reward token balance is claimed\n /// @param erc20 The ERC20 of the reward token\n /// @param amount {qTok}\n event RewardsClaimed(IERC20 indexed erc20, uint256 amount);\n\n /// Claim rewards earned by holding a balance of the ERC20 token\n /// Must emit `RewardsClaimed` for each token rewards are claimed for\n /// @custom:interaction\n function claimRewards() external;\n}\n\n/**\n * @title IRewardableComponent\n * @notice A simple interface mixin to support claiming of rewards.\n */\ninterface IRewardableComponent is IRewardable {\n /// Claim rewards for a single ERC20\n /// Must emit `RewardsClaimed` for each token rewards are claimed for\n /// @custom:interaction\n function claimRewardsSingle(IERC20 erc20) external;\n}\n"
},
"contracts/interfaces/IRToken.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n// solhint-disable-next-line max-line-length\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../libraries/Fixed.sol\";\nimport \"../libraries/Throttle.sol\";\nimport \"./IAsset.sol\";\nimport \"./IComponent.sol\";\nimport \"./IMain.sol\";\nimport \"./IRewardable.sol\";\n\n/**\n * @title IRToken\n * @notice An RToken is an ERC20 that is permissionlessly issuable/redeemable and tracks an\n * exchange rate against a single unit: baskets, or {BU} in our type notation.\n */\ninterface IRToken is IComponent, IERC20MetadataUpgradeable, IERC20PermitUpgradeable {\n /// Emitted when an issuance of RToken occurs, whether it occurs via slow minting or not\n /// @param issuer The address holding collateral tokens\n /// @param recipient The address of the recipient of the RTokens\n /// @param amount The quantity of RToken being issued\n /// @param baskets The corresponding number of baskets\n event Issuance(\n address indexed issuer,\n address indexed recipient,\n uint256 amount,\n uint192 baskets\n );\n\n /// Emitted when a redemption of RToken occurs\n /// @param redeemer The address holding RToken\n /// @param recipient The address of the account receiving the backing collateral tokens\n /// @param amount The quantity of RToken being redeemed\n /// @param baskets The corresponding number of baskets\n /// @param amount {qRTok} The amount of RTokens canceled\n event Redemption(\n address indexed redeemer,\n address indexed recipient,\n uint256 amount,\n uint192 baskets\n );\n\n /// Emitted when the number of baskets needed changes\n /// @param oldBasketsNeeded Previous number of baskets units needed\n /// @param newBasketsNeeded New number of basket units needed\n event BasketsNeededChanged(uint192 oldBasketsNeeded, uint192 newBasketsNeeded);\n\n /// Emitted when RToken is melted, i.e the RToken supply is decreased but basketsNeeded is not\n /// @param amount {qRTok}\n event Melted(uint256 amount);\n\n /// Emitted when issuance SupplyThrottle params are set\n event IssuanceThrottleSet(ThrottleLib.Params oldVal, ThrottleLib.Params newVal);\n\n /// Emitted when redemption SupplyThrottle params are set\n event RedemptionThrottleSet(ThrottleLib.Params oldVal, ThrottleLib.Params newVal);\n\n // Initialization\n function init(\n IMain main_,\n string memory name_,\n string memory symbol_,\n string memory mandate_,\n ThrottleLib.Params calldata issuanceThrottleParams,\n ThrottleLib.Params calldata redemptionThrottleParams\n ) external;\n\n /// Issue an RToken with basket collateral\n /// @param amount {qRTok} The quantity of RToken to issue\n /// @custom:interaction\n function issue(uint256 amount) external;\n\n /// Issue an RToken with basket collateral, to a particular recipient\n /// @param recipient The address to receive the issued RTokens\n /// @param amount {qRTok} The quantity of RToken to issue\n /// @custom:interaction\n function issueTo(address recipient, uint256 amount) external;\n\n /// Redeem RToken for basket collateral\n /// @dev Use redeemCustom for non-current baskets\n /// @param amount {qRTok} The quantity {qRToken} of RToken to redeem\n /// @custom:interaction\n function redeem(uint256 amount) external;\n\n /// Redeem RToken for basket collateral to a particular recipient\n /// @dev Use redeemCustom for non-current baskets\n /// @param recipient The address to receive the backing collateral tokens\n /// @param amount {qRTok} The quantity {qRToken} of RToken to redeem\n /// @custom:interaction\n function redeemTo(address recipient, uint256 amount) external;\n\n /// Redeem RToken for a linear combination of historical baskets, to a particular recipient\n /// @dev Allows partial redemptions up to the minAmounts\n /// @param recipient The address to receive the backing collateral tokens\n /// @param amount {qRTok} The quantity {qRToken} of RToken to redeem\n /// @param basketNonces An array of basket nonces to do redemption from\n /// @param portions {1} An array of Fix quantities that must add up to FIX_ONE\n /// @param expectedERC20sOut An array of ERC20s expected out\n /// @param minAmounts {qTok} The minimum ERC20 quantities the caller should receive\n /// @custom:interaction\n function redeemCustom(\n address recipient,\n uint256 amount,\n uint48[] memory basketNonces,\n uint192[] memory portions,\n address[] memory expectedERC20sOut,\n uint256[] memory minAmounts\n ) external;\n\n /// Mint an amount of RToken equivalent to baskets BUs, scaling basketsNeeded up\n /// Callable only by BackingManager\n /// @param baskets {BU} The number of baskets to mint RToken for\n /// @custom:protected\n function mint(uint192 baskets) external;\n\n /// Melt a quantity of RToken from the caller's account\n /// @param amount {qRTok} The amount to be melted\n /// @custom:protected\n function melt(uint256 amount) external;\n\n /// Burn an amount of RToken from caller's account and scale basketsNeeded down\n /// Callable only by BackingManager\n /// @custom:protected\n function dissolve(uint256 amount) external;\n\n /// Set the number of baskets needed directly, callable only by the BackingManager\n /// @param basketsNeeded {BU} The number of baskets to target\n /// needed range: pretty interesting\n /// @custom:protected\n function setBasketsNeeded(uint192 basketsNeeded) external;\n\n /// @return {BU} How many baskets are being targeted\n function basketsNeeded() external view returns (uint192);\n\n /// @return {qRTok} The maximum issuance that can be performed in the current block\n function issuanceAvailable() external view returns (uint256);\n\n /// @return {qRTok} The maximum redemption that can be performed in the current block\n function redemptionAvailable() external view returns (uint256);\n}\n\ninterface TestIRToken is IRToken {\n function setIssuanceThrottleParams(ThrottleLib.Params calldata) external;\n\n function setRedemptionThrottleParams(ThrottleLib.Params calldata) external;\n\n function issuanceThrottleParams() external view returns (ThrottleLib.Params memory);\n\n function redemptionThrottleParams() external view returns (ThrottleLib.Params memory);\n\n function increaseAllowance(address, uint256) external returns (bool);\n\n function decreaseAllowance(address, uint256) external returns (bool);\n\n function monetizeDonations(IERC20) external;\n}\n"
},
"contracts/interfaces/IStRSR.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n// solhint-disable-next-line max-line-length\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../libraries/Fixed.sol\";\nimport \"./IComponent.sol\";\nimport \"./IMain.sol\";\n\n/**\n * @title IStRSR\n * @notice An ERC20 token representing shares of the RSR over-collateralization pool.\n *\n * StRSR permits the BackingManager to take RSR in times of need. In return, the BackingManager\n * benefits the StRSR pool with RSR rewards purchased with a portion of its revenue.\n *\n * In the absence of collateral default or losses due to slippage, StRSR should have a\n * monotonically increasing exchange rate with respect to RSR, meaning that over time\n * StRSR is redeemable for more RSR. It is non-rebasing.\n */\ninterface IStRSR is IERC20MetadataUpgradeable, IERC20PermitUpgradeable, IComponent {\n /// Emitted when RSR is staked\n /// @param era The era at time of staking\n /// @param staker The address of the staker\n /// @param rsrAmount {qRSR} How much RSR was staked\n /// @param stRSRAmount {qStRSR} How much stRSR was minted by this staking\n event Staked(\n uint256 indexed era,\n address indexed staker,\n uint256 rsrAmount,\n uint256 stRSRAmount\n );\n\n /// Emitted when an unstaking is started\n /// @param draftId The id of the draft.\n /// @param draftEra The era of the draft.\n /// @param staker The address of the unstaker\n /// The triple (staker, draftEra, draftId) is a unique ID\n /// @param rsrAmount {qRSR} How much RSR this unstaking will be worth, absent seizures\n /// @param stRSRAmount {qStRSR} How much stRSR was burned by this unstaking\n event UnstakingStarted(\n uint256 indexed draftId,\n uint256 indexed draftEra,\n address indexed staker,\n uint256 rsrAmount,\n uint256 stRSRAmount,\n uint256 availableAt\n );\n\n /// Emitted when RSR is unstaked\n /// @param firstId The beginning of the range of draft IDs withdrawn in this transaction\n /// @param endId The end of range of draft IDs withdrawn in this transaction\n /// (ID i was withdrawn if firstId <= i < endId)\n /// @param draftEra The era of the draft.\n /// The triple (staker, draftEra, id) is a unique ID among drafts\n /// @param staker The address of the unstaker\n\n /// @param rsrAmount {qRSR} How much RSR this unstaking was worth\n event UnstakingCompleted(\n uint256 indexed firstId,\n uint256 indexed endId,\n uint256 draftEra,\n address indexed staker,\n uint256 rsrAmount\n );\n\n /// Emitted when RSR unstaking is cancelled\n /// @param firstId The beginning of the range of draft IDs withdrawn in this transaction\n /// @param endId The end of range of draft IDs withdrawn in this transaction\n /// (ID i was withdrawn if firstId <= i < endId)\n /// @param draftEra The era of the draft.\n /// The triple (staker, draftEra, id) is a unique ID among drafts\n /// @param staker The address of the unstaker\n\n /// @param rsrAmount {qRSR} How much RSR this unstaking was worth\n event UnstakingCancelled(\n uint256 indexed firstId,\n uint256 indexed endId,\n uint256 draftEra,\n address indexed staker,\n uint256 rsrAmount\n );\n\n /// Emitted whenever the exchange rate changes\n event ExchangeRateSet(uint192 oldVal, uint192 newVal);\n\n /// Emitted whenever RSR are paids out\n event RewardsPaid(uint256 rsrAmt);\n\n /// Emitted if all the RSR in the staking pool is seized and all balances are reset to zero.\n event AllBalancesReset(uint256 indexed newEra);\n /// Emitted if all the RSR in the unstakin pool is seized, and all ongoing unstaking is voided.\n event AllUnstakingReset(uint256 indexed newEra);\n\n event UnstakingDelaySet(uint48 oldVal, uint48 newVal);\n event RewardRatioSet(uint192 oldVal, uint192 newVal);\n event WithdrawalLeakSet(uint192 oldVal, uint192 newVal);\n\n // Initialization\n function init(\n IMain main_,\n string memory name_,\n string memory symbol_,\n uint48 unstakingDelay_,\n uint192 rewardRatio_,\n uint192 withdrawalLeak_\n ) external;\n\n /// Gather and payout rewards from rsrTrader\n /// @custom:interaction\n function payoutRewards() external;\n\n /// Stakes an RSR `amount` on the corresponding RToken to earn yield and over-collateralized\n /// the system\n /// @param amount {qRSR}\n /// @custom:interaction\n function stake(uint256 amount) external;\n\n /// Begins a delayed unstaking for `amount` stRSR\n /// @param amount {qStRSR}\n /// @custom:interaction\n function unstake(uint256 amount) external;\n\n /// Complete delayed unstaking for the account, up to (but not including!) `endId`\n /// @custom:interaction\n function withdraw(address account, uint256 endId) external;\n\n /// Cancel unstaking for the account, up to (but not including!) `endId`\n /// @custom:interaction\n function cancelUnstake(uint256 endId) external;\n\n /// Seize RSR, only callable by main.backingManager()\n /// @custom:protected\n function seizeRSR(uint256 amount) external;\n\n /// Reset all stakes and advance era\n /// @custom:governance\n function resetStakes() external;\n\n /// Return the maximum valid value of endId such that withdraw(endId) should immediately work\n function endIdForWithdraw(address account) external view returns (uint256 endId);\n\n /// @return {qRSR/qStRSR} The exchange rate between RSR and StRSR\n function exchangeRate() external view returns (uint192);\n}\n\ninterface TestIStRSR is IStRSR {\n function rewardRatio() external view returns (uint192);\n\n function setRewardRatio(uint192) external;\n\n function unstakingDelay() external view returns (uint48);\n\n function setUnstakingDelay(uint48) external;\n\n function withdrawalLeak() external view returns (uint192);\n\n function setWithdrawalLeak(uint192) external;\n\n function increaseAllowance(address, uint256) external returns (bool);\n\n function decreaseAllowance(address, uint256) external returns (bool);\n\n /// @return {qStRSR/qRSR} The exchange rate between StRSR and RSR\n function exchangeRate() external view returns (uint192);\n}\n"
},
"contracts/interfaces/ITrade.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"./IBroker.sol\";\nimport \"./IVersioned.sol\";\n\nenum TradeStatus {\n NOT_STARTED, // before init()\n OPEN, // after init() and before settle()\n CLOSED, // after settle()\n // === Intermediate-tx state ===\n PENDING // during init() or settle() (reentrancy protection)\n}\n\n/**\n * Simple generalized trading interface for all Trade contracts to obey\n *\n * Usage: if (canSettle()) settle()\n */\ninterface ITrade is IVersioned {\n /// Complete the trade and transfer tokens back to the origin trader\n /// @return soldAmt {qSellTok} The quantity of tokens sold\n /// @return boughtAmt {qBuyTok} The quantity of tokens bought\n function settle() external returns (uint256 soldAmt, uint256 boughtAmt);\n\n function sell() external view returns (IERC20Metadata);\n\n function buy() external view returns (IERC20Metadata);\n\n /// @return {tok} The sell amount of the trade, in whole tokens\n function sellAmount() external view returns (uint192);\n\n /// @return The timestamp at which the trade is projected to become settle-able\n function endTime() external view returns (uint48);\n\n /// @return True if the trade can be settled\n /// @dev Should be guaranteed to be true eventually as an invariant\n function canSettle() external view returns (bool);\n\n /// @return TradeKind.DUTCH_AUCTION or TradeKind.BATCH_AUCTION\n // solhint-disable-next-line func-name-mixedcase\n function KIND() external view returns (TradeKind);\n}\n"
},
"contracts/interfaces/ITrading.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../libraries/Fixed.sol\";\nimport \"./IAsset.sol\";\nimport \"./IComponent.sol\";\nimport \"./ITrade.sol\";\nimport \"./IRewardable.sol\";\n\n/**\n * @title ITrading\n * @notice Common events and refresher function for all Trading contracts\n */\ninterface ITrading is IComponent, IRewardableComponent {\n event MaxTradeSlippageSet(uint192 oldVal, uint192 newVal);\n event MinTradeVolumeSet(uint192 oldVal, uint192 newVal);\n\n /// Emitted when a trade is started\n /// @param trade The one-time-use trade contract that was just deployed\n /// @param sell The token to sell\n /// @param buy The token to buy\n /// @param sellAmount {qSellTok} The quantity of the selling token\n /// @param minBuyAmount {qBuyTok} The minimum quantity of the buying token to accept\n event TradeStarted(\n ITrade indexed trade,\n IERC20 indexed sell,\n IERC20 indexed buy,\n uint256 sellAmount,\n uint256 minBuyAmount\n );\n\n /// Emitted after a trade ends\n /// @param trade The one-time-use trade contract\n /// @param sell The token to sell\n /// @param buy The token to buy\n /// @param sellAmount {qSellTok} The quantity of the token sold\n /// @param buyAmount {qBuyTok} The quantity of the token bought\n event TradeSettled(\n ITrade indexed trade,\n IERC20 indexed sell,\n IERC20 indexed buy,\n uint256 sellAmount,\n uint256 buyAmount\n );\n\n /// Settle a single trade, expected to be used with multicall for efficient mass settlement\n /// @param sell The sell token in the trade\n /// @return The trade settled\n /// @custom:refresher\n function settleTrade(IERC20 sell) external returns (ITrade);\n\n /// @return {%} The maximum trade slippage acceptable\n function maxTradeSlippage() external view returns (uint192);\n\n /// @return {UoA} The minimum trade volume in UoA, applies to all assets\n function minTradeVolume() external view returns (uint192);\n\n /// @return The ongoing trade for a sell token, or the zero address\n function trades(IERC20 sell) external view returns (ITrade);\n\n /// @return The number of ongoing trades open\n function tradesOpen() external view returns (uint48);\n\n /// @return The number of total trades ever opened\n function tradesNonce() external view returns (uint256);\n}\n\ninterface TestITrading is ITrading {\n /// @custom:governance\n function setMaxTradeSlippage(uint192 val) external;\n\n /// @custom:governance\n function setMinTradeVolume(uint192 val) external;\n}\n"
},
"contracts/interfaces/IVersioned.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\ninterface IVersioned {\n function version() external view returns (string memory);\n}\n"
},
"contracts/libraries/Fixed.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\n// solhint-disable func-name-mixedcase func-visibility\n// slither-disable-start divide-before-multiply\npragma solidity ^0.8.19;\n\n/// @title FixedPoint, a fixed-point arithmetic library defining the custom type uint192\n/// @author Matt Elder <matt.elder@reserve.org> and the Reserve Team <https://reserve.org>\n\n/** The logical type `uint192 ` is a 192 bit value, representing an 18-decimal Fixed-point\n fractional value. This is what's described in the Solidity documentation as\n \"fixed192x18\" -- a value represented by 192 bits, that makes 18 digits available to\n the right of the decimal point.\n\n The range of values that uint192 can represent is about [-1.7e20, 1.7e20].\n Unless a function explicitly says otherwise, it will fail on overflow.\n To be clear, the following should hold:\n toFix(0) == 0\n toFix(1) == 1e18\n*/\n\n// Analysis notes:\n// Every function should revert iff its result is out of bounds.\n// Unless otherwise noted, when a rounding mode is given, that mode is applied to\n// a single division that may happen as the last step in the computation.\n// Unless otherwise noted, when a rounding mode is *not* given but is needed, it's FLOOR.\n// For each, we comment:\n// - @return is the value expressed in \"value space\", where uint192(1e18) \"is\" 1.0\n// - as-ints: is the value expressed in \"implementation space\", where uint192(1e18) \"is\" 1e18\n// The \"@return\" expression is suitable for actually using the library\n// The \"as-ints\" expression is suitable for testing\n\n// A uint value passed to this library was out of bounds for uint192 operations\nerror UIntOutOfBounds();\nbytes32 constant UIntOutofBoundsHash = keccak256(abi.encodeWithSignature(\"UIntOutOfBounds()\"));\n\n// Used by P1 implementation for easier casting\nuint256 constant FIX_ONE_256 = 1e18;\nuint8 constant FIX_DECIMALS = 18;\n\n// If a particular uint192 is represented by the uint192 n, then the uint192 represents the\n// value n/FIX_SCALE.\nuint64 constant FIX_SCALE = 1e18;\n\n// FIX_SCALE Squared:\nuint128 constant FIX_SCALE_SQ = 1e36;\n\n// The largest integer that can be converted to uint192 .\n// This is a bit bigger than 3.1e39\nuint192 constant FIX_MAX_INT = type(uint192).max / FIX_SCALE;\n\nuint192 constant FIX_ZERO = 0; // The uint192 representation of zero.\nuint192 constant FIX_ONE = FIX_SCALE; // The uint192 representation of one.\nuint192 constant FIX_MAX = type(uint192).max; // The largest uint192. (Not an integer!)\nuint192 constant FIX_MIN = 0; // The smallest uint192.\n\n/// An enum that describes a rounding approach for converting to ints\nenum RoundingMode {\n FLOOR, // Round towards zero\n ROUND, // Round to the nearest int\n CEIL // Round away from zero\n}\n\nRoundingMode constant FLOOR = RoundingMode.FLOOR;\nRoundingMode constant ROUND = RoundingMode.ROUND;\nRoundingMode constant CEIL = RoundingMode.CEIL;\n\n/* @dev Solidity 0.8.x only allows you to change one of type or size per type conversion.\n Thus, all the tedious-looking double conversions like uint256(uint256 (foo))\n See: https://docs.soliditylang.org/en/v0.8.17/080-breaking-changes.html#new-restrictions\n */\n\n/// Explicitly convert a uint256 to a uint192. Revert if the input is out of bounds.\nfunction _safeWrap(uint256 x) pure returns (uint192) {\n if (FIX_MAX < x) revert UIntOutOfBounds();\n return uint192(x);\n}\n\n/// Convert a uint to its Fix representation.\n/// @return x\n// as-ints: x * 1e18\nfunction toFix(uint256 x) pure returns (uint192) {\n return _safeWrap(x * FIX_SCALE);\n}\n\n/// Convert a uint to its fixed-point representation, and left-shift its value `shiftLeft`\n/// decimal digits.\n/// @return x * 10**shiftLeft\n// as-ints: x * 10**(shiftLeft + 18)\nfunction shiftl_toFix(uint256 x, int8 shiftLeft) pure returns (uint192) {\n return shiftl_toFix(x, shiftLeft, FLOOR);\n}\n\n/// @return x * 10**shiftLeft\n// as-ints: x * 10**(shiftLeft + 18)\nfunction shiftl_toFix(\n uint256 x,\n int8 shiftLeft,\n RoundingMode rounding\n) pure returns (uint192) {\n // conditions for avoiding overflow\n if (x == 0) return 0;\n if (shiftLeft <= -96) return (rounding == CEIL ? 1 : 0); // 0 < uint.max / 10**77 < 0.5\n if (40 <= shiftLeft) revert UIntOutOfBounds(); // 10**56 < FIX_MAX < 10**57\n\n shiftLeft += 18;\n\n uint256 coeff = 10**abs(shiftLeft);\n uint256 shifted = (shiftLeft >= 0) ? x * coeff : _divrnd(x, coeff, rounding);\n\n return _safeWrap(shifted);\n}\n\n/// Divide a uint by a uint192, yielding a uint192\n/// This may also fail if the result is MIN_uint192! not fixing this for optimization's sake.\n/// @return x / y\n// as-ints: x * 1e36 / y\nfunction divFix(uint256 x, uint192 y) pure returns (uint192) {\n // If we didn't have to worry about overflow, we'd just do `return x * 1e36 / _y`\n // If it's safe to do this operation the easy way, do it:\n if (x < uint256(type(uint256).max / FIX_SCALE_SQ)) {\n return _safeWrap(uint256(x * FIX_SCALE_SQ) / y);\n } else {\n return _safeWrap(mulDiv256(x, FIX_SCALE_SQ, y));\n }\n}\n\n/// Divide a uint by a uint, yielding a uint192\n/// @return x / y\n// as-ints: x * 1e18 / y\nfunction divuu(uint256 x, uint256 y) pure returns (uint192) {\n return _safeWrap(mulDiv256(FIX_SCALE, x, y));\n}\n\n/// @return min(x,y)\n// as-ints: min(x,y)\nfunction fixMin(uint192 x, uint192 y) pure returns (uint192) {\n return x < y ? x : y;\n}\n\n/// @return max(x,y)\n// as-ints: max(x,y)\nfunction fixMax(uint192 x, uint192 y) pure returns (uint192) {\n return x > y ? x : y;\n}\n\n/// @return absoluteValue(x,y)\n// as-ints: absoluteValue(x,y)\nfunction abs(int256 x) pure returns (uint256) {\n return x < 0 ? uint256(-x) : uint256(x);\n}\n\n/// Divide two uints, returning a uint, using rounding mode `rounding`.\n/// @return numerator / divisor\n// as-ints: numerator / divisor\nfunction _divrnd(\n uint256 numerator,\n uint256 divisor,\n RoundingMode rounding\n) pure returns (uint256) {\n uint256 result = numerator / divisor;\n\n if (rounding == FLOOR) return result;\n\n if (rounding == ROUND) {\n if (numerator % divisor > (divisor - 1) / 2) {\n result++;\n }\n } else {\n if (numerator % divisor > 0) {\n result++;\n }\n }\n\n return result;\n}\n\nlibrary FixLib {\n /// Again, all arithmetic functions fail if and only if the result is out of bounds.\n\n /// Convert this fixed-point value to a uint. Round towards zero if needed.\n /// @return x\n // as-ints: x / 1e18\n function toUint(uint192 x) internal pure returns (uint136) {\n return toUint(x, FLOOR);\n }\n\n /// Convert this uint192 to a uint\n /// @return x\n // as-ints: x / 1e18 with rounding\n function toUint(uint192 x, RoundingMode rounding) internal pure returns (uint136) {\n return uint136(_divrnd(uint256(x), FIX_SCALE, rounding));\n }\n\n /// Return the uint192 shifted to the left by `decimal` digits\n /// (Similar to a bitshift but in base 10)\n /// @return x * 10**decimals\n // as-ints: x * 10**decimals\n function shiftl(uint192 x, int8 decimals) internal pure returns (uint192) {\n return shiftl(x, decimals, FLOOR);\n }\n\n /// Return the uint192 shifted to the left by `decimal` digits\n /// (Similar to a bitshift but in base 10)\n /// @return x * 10**decimals\n // as-ints: x * 10**decimals\n function shiftl(\n uint192 x,\n int8 decimals,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n // Handle overflow cases\n if (x == 0) return 0;\n if (decimals <= -59) return (rounding == CEIL ? 1 : 0); // 59, because 1e58 > 2**192\n if (58 <= decimals) revert UIntOutOfBounds(); // 58, because x * 1e58 > 2 ** 192 if x != 0\n\n uint256 coeff = uint256(10**abs(decimals));\n return _safeWrap(decimals >= 0 ? x * coeff : _divrnd(x, coeff, rounding));\n }\n\n /// Add a uint192 to this uint192\n /// @return x + y\n // as-ints: x + y\n function plus(uint192 x, uint192 y) internal pure returns (uint192) {\n return x + y;\n }\n\n /// Add a uint to this uint192\n /// @return x + y\n // as-ints: x + y*1e18\n function plusu(uint192 x, uint256 y) internal pure returns (uint192) {\n return _safeWrap(x + y * FIX_SCALE);\n }\n\n /// Subtract a uint192 from this uint192\n /// @return x - y\n // as-ints: x - y\n function minus(uint192 x, uint192 y) internal pure returns (uint192) {\n return x - y;\n }\n\n /// Subtract a uint from this uint192\n /// @return x - y\n // as-ints: x - y*1e18\n function minusu(uint192 x, uint256 y) internal pure returns (uint192) {\n return _safeWrap(uint256(x) - uint256(y * FIX_SCALE));\n }\n\n /// Multiply this uint192 by a uint192\n /// Round truncated values to the nearest available value. 5e-19 rounds away from zero.\n /// @return x * y\n // as-ints: x * y/1e18 [division using ROUND, not FLOOR]\n function mul(uint192 x, uint192 y) internal pure returns (uint192) {\n return mul(x, y, ROUND);\n }\n\n /// Multiply this uint192 by a uint192\n /// @return x * y\n // as-ints: x * y/1e18\n function mul(\n uint192 x,\n uint192 y,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n return _safeWrap(_divrnd(uint256(x) * uint256(y), FIX_SCALE, rounding));\n }\n\n /// Multiply this uint192 by a uint\n /// @return x * y\n // as-ints: x * y\n function mulu(uint192 x, uint256 y) internal pure returns (uint192) {\n return _safeWrap(x * y);\n }\n\n /// Divide this uint192 by a uint192\n /// @return x / y\n // as-ints: x * 1e18 / y\n function div(uint192 x, uint192 y) internal pure returns (uint192) {\n return div(x, y, FLOOR);\n }\n\n /// Divide this uint192 by a uint192\n /// @return x / y\n // as-ints: x * 1e18 / y\n function div(\n uint192 x,\n uint192 y,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n // Multiply-in FIX_SCALE before dividing by y to preserve precision.\n return _safeWrap(_divrnd(uint256(x) * FIX_SCALE, y, rounding));\n }\n\n /// Divide this uint192 by a uint\n /// @return x / y\n // as-ints: x / y\n function divu(uint192 x, uint256 y) internal pure returns (uint192) {\n return divu(x, y, FLOOR);\n }\n\n /// Divide this uint192 by a uint\n /// @return x / y\n // as-ints: x / y\n function divu(\n uint192 x,\n uint256 y,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n return _safeWrap(_divrnd(x, y, rounding));\n }\n\n uint64 constant FIX_HALF = uint64(FIX_SCALE) / 2;\n\n /// Raise this uint192 to a nonnegative integer power. Requires that x_ <= FIX_ONE\n /// Gas cost is O(lg(y)), precision is +- 1e-18.\n /// @return x_ ** y\n // as-ints: x_ ** y / 1e18**(y-1) <- technically correct for y = 0. :D\n function powu(uint192 x_, uint48 y) internal pure returns (uint192) {\n require(x_ <= FIX_ONE);\n if (y == 1) return x_;\n if (x_ == FIX_ONE || y == 0) return FIX_ONE;\n uint256 x = uint256(x_) * FIX_SCALE; // x is D36\n uint256 result = FIX_SCALE_SQ; // result is D36\n while (true) {\n if (y & 1 == 1) result = (result * x + FIX_SCALE_SQ / 2) / FIX_SCALE_SQ;\n if (y <= 1) break;\n y = (y >> 1);\n x = (x * x + FIX_SCALE_SQ / 2) / FIX_SCALE_SQ;\n }\n return _safeWrap(result / FIX_SCALE);\n }\n\n /// Comparison operators...\n function lt(uint192 x, uint192 y) internal pure returns (bool) {\n return x < y;\n }\n\n function lte(uint192 x, uint192 y) internal pure returns (bool) {\n return x <= y;\n }\n\n function gt(uint192 x, uint192 y) internal pure returns (bool) {\n return x > y;\n }\n\n function gte(uint192 x, uint192 y) internal pure returns (bool) {\n return x >= y;\n }\n\n function eq(uint192 x, uint192 y) internal pure returns (bool) {\n return x == y;\n }\n\n function neq(uint192 x, uint192 y) internal pure returns (bool) {\n return x != y;\n }\n\n /// Return whether or not this uint192 is less than epsilon away from y.\n /// @return |x - y| < epsilon\n // as-ints: |x - y| < epsilon\n function near(\n uint192 x,\n uint192 y,\n uint192 epsilon\n ) internal pure returns (bool) {\n uint192 diff = x <= y ? y - x : x - y;\n return diff < epsilon;\n }\n\n // ================ Chained Operations ================\n // The operation foo_bar() always means:\n // Do foo() followed by bar(), and overflow only if the _end_ result doesn't fit in an uint192\n\n /// Shift this uint192 left by `decimals` digits, and convert to a uint\n /// @return x * 10**decimals\n // as-ints: x * 10**(decimals - 18)\n function shiftl_toUint(uint192 x, int8 decimals) internal pure returns (uint256) {\n return shiftl_toUint(x, decimals, FLOOR);\n }\n\n /// Shift this uint192 left by `decimals` digits, and convert to a uint.\n /// @return x * 10**decimals\n // as-ints: x * 10**(decimals - 18)\n function shiftl_toUint(\n uint192 x,\n int8 decimals,\n RoundingMode rounding\n ) internal pure returns (uint256) {\n // Handle overflow cases\n if (x == 0) return 0; // always computable, no matter what decimals is\n if (decimals <= -42) return (rounding == CEIL ? 1 : 0);\n if (96 <= decimals) revert UIntOutOfBounds();\n\n decimals -= 18; // shift so that toUint happens at the same time.\n\n uint256 coeff = uint256(10**abs(decimals));\n return decimals >= 0 ? uint256(x * coeff) : uint256(_divrnd(x, coeff, rounding));\n }\n\n /// Multiply this uint192 by a uint, and output the result as a uint\n /// @return x * y\n // as-ints: x * y / 1e18\n function mulu_toUint(uint192 x, uint256 y) internal pure returns (uint256) {\n return mulDiv256(uint256(x), y, FIX_SCALE);\n }\n\n /// Multiply this uint192 by a uint, and output the result as a uint\n /// @return x * y\n // as-ints: x * y / 1e18\n function mulu_toUint(\n uint192 x,\n uint256 y,\n RoundingMode rounding\n ) internal pure returns (uint256) {\n return mulDiv256(uint256(x), y, FIX_SCALE, rounding);\n }\n\n /// Multiply this uint192 by a uint192 and output the result as a uint\n /// @return x * y\n // as-ints: x * y / 1e36\n function mul_toUint(uint192 x, uint192 y) internal pure returns (uint256) {\n return mulDiv256(uint256(x), uint256(y), FIX_SCALE_SQ);\n }\n\n /// Multiply this uint192 by a uint192 and output the result as a uint\n /// @return x * y\n // as-ints: x * y / 1e36\n function mul_toUint(\n uint192 x,\n uint192 y,\n RoundingMode rounding\n ) internal pure returns (uint256) {\n return mulDiv256(uint256(x), uint256(y), FIX_SCALE_SQ, rounding);\n }\n\n /// Compute x * y / z avoiding intermediate overflow\n /// @dev Only use if you need to avoid overflow; costlier than x * y / z\n /// @return x * y / z\n // as-ints: x * y / z\n function muluDivu(\n uint192 x,\n uint256 y,\n uint256 z\n ) internal pure returns (uint192) {\n return muluDivu(x, y, z, FLOOR);\n }\n\n /// Compute x * y / z, avoiding intermediate overflow\n /// @dev Only use if you need to avoid overflow; costlier than x * y / z\n /// @return x * y / z\n // as-ints: x * y / z\n function muluDivu(\n uint192 x,\n uint256 y,\n uint256 z,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n return _safeWrap(mulDiv256(x, y, z, rounding));\n }\n\n /// Compute x * y / z on Fixes, avoiding intermediate overflow\n /// @dev Only use if you need to avoid overflow; costlier than x * y / z\n /// @return x * y / z\n // as-ints: x * y / z\n function mulDiv(\n uint192 x,\n uint192 y,\n uint192 z\n ) internal pure returns (uint192) {\n return mulDiv(x, y, z, FLOOR);\n }\n\n /// Compute x * y / z on Fixes, avoiding intermediate overflow\n /// @dev Only use if you need to avoid overflow; costlier than x * y / z\n /// @return x * y / z\n // as-ints: x * y / z\n function mulDiv(\n uint192 x,\n uint192 y,\n uint192 z,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n return _safeWrap(mulDiv256(x, y, z, rounding));\n }\n\n // === safe*() ===\n\n /// Multiply two fixes, rounding up to FIX_MAX and down to 0\n /// @param a First param to multiply\n /// @param b Second param to multiply\n function safeMul(\n uint192 a,\n uint192 b,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n // untestable:\n // a will never = 0 here because of the check in _price()\n if (a == 0 || b == 0) return 0;\n // untestable:\n // a = FIX_MAX iff b = 0\n if (a == FIX_MAX || b == FIX_MAX) return FIX_MAX;\n\n // return FIX_MAX instead of throwing overflow errors.\n unchecked {\n // p and mul *are* Fix values, so have 18 decimals (D18)\n uint256 rawDelta = uint256(b) * a; // {D36} = {D18} * {D18}\n // if we overflowed, then return FIX_MAX\n if (rawDelta / b != a) return FIX_MAX;\n uint256 shiftDelta = rawDelta;\n\n // add in rounding\n if (rounding == RoundingMode.ROUND) shiftDelta += (FIX_ONE / 2);\n else if (rounding == RoundingMode.CEIL) shiftDelta += FIX_ONE - 1;\n\n // untestable (here there be dragons):\n // (below explanation is for the ROUND case, but it extends to the FLOOR/CEIL too)\n // A) shiftDelta = rawDelta + (FIX_ONE / 2)\n // shiftDelta overflows if:\n // B) shiftDelta = MAX_UINT256 - FIX_ONE/2 + 1\n // rawDelta + (FIX_ONE/2) = MAX_UINT256 - FIX_ONE/2 + 1\n // b * a = MAX_UINT256 - FIX_ONE + 1\n // therefore shiftDelta overflows if:\n // C) b = (MAX_UINT256 - FIX_ONE + 1) / a\n // MAX_UINT256 ~= 1e77 , FIX_MAX ~= 6e57 (6e20 difference in magnitude)\n // a <= 1e21 (MAX_TARGET_AMT)\n // a must be between 1e19 & 1e20 in order for b in (C) to be uint192,\n // but a would have to be < 1e18 in order for (A) to overflow\n if (shiftDelta < rawDelta) return FIX_MAX;\n\n // return FIX_MAX if return result would truncate\n if (shiftDelta / FIX_ONE > FIX_MAX) return FIX_MAX;\n\n // return _div(rawDelta, FIX_ONE, rounding)\n return uint192(shiftDelta / FIX_ONE); // {D18} = {D36} / {D18}\n }\n }\n\n /// Divide two fixes, rounding up to FIX_MAX and down to 0\n /// @param a Numerator\n /// @param b Denominator\n function safeDiv(\n uint192 a,\n uint192 b,\n RoundingMode rounding\n ) internal pure returns (uint192) {\n if (a == 0) return 0;\n if (b == 0) return FIX_MAX;\n\n uint256 raw = _divrnd(FIX_ONE_256 * a, uint256(b), rounding);\n if (raw >= FIX_MAX) return FIX_MAX;\n return uint192(raw); // don't need _safeWrap\n }\n\n /// Multiplies two fixes and divide by a third\n /// @param a First to multiply\n /// @param b Second to multiply\n /// @param c Denominator\n function safeMulDiv(\n uint192 a,\n uint192 b,\n uint192 c,\n RoundingMode rounding\n ) internal pure returns (uint192 result) {\n if (a == 0 || b == 0) return 0;\n if (a == FIX_MAX || b == FIX_MAX || c == 0) return FIX_MAX;\n\n uint256 result_256;\n unchecked {\n (uint256 hi, uint256 lo) = fullMul(a, b);\n if (hi >= c) return FIX_MAX;\n uint256 mm = mulmod(a, b, c);\n if (mm > lo) hi -= 1;\n lo -= mm;\n uint256 pow2 = c & (0 - c);\n\n uint256 c_256 = uint256(c);\n // Warning: Should not access c below this line\n\n c_256 /= pow2;\n lo /= pow2;\n lo += hi * ((0 - pow2) / pow2 + 1);\n uint256 r = 1;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n r *= 2 - c_256 * r;\n result_256 = lo * r;\n\n // Apply rounding\n if (rounding == CEIL) {\n if (mm > 0) result_256 += 1;\n } else if (rounding == ROUND) {\n if (mm > ((c_256 - 1) / 2)) result_256 += 1;\n }\n }\n\n if (result_256 >= FIX_MAX) return FIX_MAX;\n return uint192(result_256);\n }\n}\n\n// ================ a couple pure-uint helpers================\n// as-ints comments are omitted here, because they're the same as @return statements, because\n// these are all pure uint functions\n\n/// Return (x*y/z), avoiding intermediate overflow.\n// Adapted from sources:\n// https://medium.com/coinmonks/4db014e080b1, https://medium.com/wicketh/afa55870a65\n// and quite a few of the other excellent \"Mathemagic\" posts from https://medium.com/wicketh\n/// @dev Only use if you need to avoid overflow; costlier than x * y / z\n/// @return result x * y / z\nfunction mulDiv256(\n uint256 x,\n uint256 y,\n uint256 z\n) pure returns (uint256 result) {\n unchecked {\n (uint256 hi, uint256 lo) = fullMul(x, y);\n if (hi >= z) revert UIntOutOfBounds();\n uint256 mm = mulmod(x, y, z);\n if (mm > lo) hi -= 1;\n lo -= mm;\n uint256 pow2 = z & (0 - z);\n z /= pow2;\n lo /= pow2;\n lo += hi * ((0 - pow2) / pow2 + 1);\n uint256 r = 1;\n r *= 2 - z * r;\n r *= 2 - z * r;\n r *= 2 - z * r;\n r *= 2 - z * r;\n r *= 2 - z * r;\n r *= 2 - z * r;\n r *= 2 - z * r;\n r *= 2 - z * r;\n result = lo * r;\n }\n}\n\n/// Return (x*y/z), avoiding intermediate overflow.\n/// @dev Only use if you need to avoid overflow; costlier than x * y / z\n/// @return x * y / z\nfunction mulDiv256(\n uint256 x,\n uint256 y,\n uint256 z,\n RoundingMode rounding\n) pure returns (uint256) {\n uint256 result = mulDiv256(x, y, z);\n if (rounding == FLOOR) return result;\n\n uint256 mm = mulmod(x, y, z);\n if (rounding == CEIL) {\n if (mm > 0) result += 1;\n } else {\n if (mm > ((z - 1) / 2)) result += 1; // z should be z-1\n }\n return result;\n}\n\n/// Return (x*y) as a \"virtual uint512\" (lo, hi), representing (hi*2**256 + lo)\n/// Adapted from sources:\n/// https://medium.com/wicketh/27650fec525d, https://medium.com/coinmonks/4db014e080b1\n/// @dev Intended to be internal to this library\n/// @return hi (hi, lo) satisfies hi*(2**256) + lo == x * y\n/// @return lo (paired with `hi`)\nfunction fullMul(uint256 x, uint256 y) pure returns (uint256 hi, uint256 lo) {\n unchecked {\n uint256 mm = mulmod(x, y, uint256(0) - uint256(1));\n lo = x * y;\n hi = mm - lo;\n if (mm < lo) hi -= 1;\n }\n}\n// slither-disable-end divide-before-multiply\n"
},
"contracts/libraries/NetworkConfigLib.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\n/**\n * @title NetworkConfigLib\n * @notice Provides network-specific configuration parameters\n */\nlibrary NetworkConfigLib {\n error InvalidNetwork();\n\n // Returns the blocktime based on the current network (e.g. 12s for Ethereum PoS)\n // See docs/system-design.md for discussion of handling longer or shorter times\n function blocktime() internal view returns (uint48) {\n uint256 chainId = block.chainid;\n // untestable:\n // most of the branches will be shown as uncovered, because we only run coverage\n // on local Ethereum PoS network (31337). Manual testing was performed.\n if (chainId == 1 || chainId == 3 || chainId == 5 || chainId == 31337) {\n return 12; // Ethereum PoS, Goerli, HH (tests)\n } else if (chainId == 8453 || chainId == 84531) {\n return 2; // Base, Base Goerli\n } else {\n revert InvalidNetwork();\n }\n }\n}\n"
},
"contracts/libraries/Throttle.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"./Fixed.sol\";\n\nuint48 constant ONE_HOUR = 3600; // {seconds/hour}\n\n/**\n * @title ThrottleLib\n * A library that implements a usage throttle that can be used to ensure net issuance\n * or net redemption for an RToken never exceeds some bounds per unit time (hour).\n *\n * It is expected for the RToken to use this library with two instances, one for issuance\n * and one for redemption. Issuance causes the available redemption amount to increase, and\n * visa versa.\n */\nlibrary ThrottleLib {\n using FixLib for uint192;\n\n struct Params {\n uint256 amtRate; // {qRTok/hour} a quantity of RToken hourly; cannot be 0\n uint192 pctRate; // {1/hour} a fraction of RToken hourly; can be 0\n }\n\n struct Throttle {\n // === Gov params ===\n Params params;\n // === Cache ===\n uint48 lastTimestamp; // {seconds}\n uint256 lastAvailable; // {qRTok}\n }\n\n /// Reverts if usage amount exceeds available amount\n /// @param supply {qRTok} Total RToken supply beforehand\n /// @param amount {qRTok} Amount of RToken to use. Should be negative for the issuance\n /// throttle during redemption and for the redemption throttle during issuance.\n function useAvailable(\n Throttle storage throttle,\n uint256 supply,\n int256 amount\n ) internal {\n // untestable: amtRate will always be greater > 0 due to previous validations\n if (throttle.params.amtRate == 0 && throttle.params.pctRate == 0) return;\n\n // Calculate hourly limit\n uint256 limit = hourlyLimit(throttle, supply); // {qRTok}\n\n // Calculate available amount before supply change\n uint256 available = currentlyAvailable(throttle, limit);\n\n // Update throttle.timestamp if available amount changed or at limit\n if (available != throttle.lastAvailable || available == limit) {\n throttle.lastTimestamp = uint48(block.timestamp);\n }\n\n // Update throttle.lastAvailable\n if (amount > 0) {\n require(uint256(amount) <= available, \"supply change throttled\");\n available -= uint256(amount);\n // untestable: the final else statement, amount will never be 0\n } else if (amount < 0) {\n available += uint256(-amount);\n }\n throttle.lastAvailable = available;\n }\n\n /// @param limit {qRTok/hour} The hourly limit\n /// @return available {qRTok} Amount currently available for consumption\n function currentlyAvailable(Throttle storage throttle, uint256 limit)\n internal\n view\n returns (uint256 available)\n {\n uint48 delta = uint48(block.timestamp) - throttle.lastTimestamp; // {seconds}\n available = throttle.lastAvailable + (limit * delta) / ONE_HOUR;\n if (available > limit) available = limit;\n }\n\n /// @return limit {qRTok} The hourly limit\n function hourlyLimit(Throttle storage throttle, uint256 supply)\n internal\n view\n returns (uint256 limit)\n {\n Params storage params = throttle.params;\n\n // Calculate hourly limit as: max(params.amtRate, supply.mul(params.pctRate))\n limit = (supply * params.pctRate) / FIX_ONE_256; // {qRTok}\n if (params.amtRate > limit) limit = params.amtRate;\n }\n}\n"
},
"contracts/mixins/Versioned.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"../interfaces/IVersioned.sol\";\n\n// This value should be updated on each release\nstring constant VERSION = \"3.3.0\";\n\n/**\n * @title Versioned\n * @notice A mix-in to track semantic versioning uniformly across contracts.\n */\nabstract contract Versioned is IVersioned {\n function version() public pure virtual override returns (string memory) {\n return VERSION;\n }\n}\n"
},
"contracts/plugins/trading/DutchTrade.sol": {
"content": "// SPDX-License-Identifier: BlueOak-1.0.0\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../../libraries/Fixed.sol\";\nimport \"../../libraries/NetworkConfigLib.sol\";\nimport \"../../interfaces/IAsset.sol\";\nimport \"../../interfaces/IBroker.sol\";\nimport \"../../interfaces/ITrade.sol\";\nimport \"../../mixins/Versioned.sol\";\n\ninterface IDutchTradeCallee {\n function dutchTradeCallback(\n address buyToken,\n // {qBuyTok}\n uint256 buyAmount,\n bytes calldata data\n ) external;\n}\n\nenum BidType {\n NONE,\n CALLBACK,\n TRANSFER\n}\n\n// A dutch auction in 4 parts:\n// 1. 0% - 20%: Geometric decay from 1000x the bestPrice to ~1.5x the bestPrice\n// 2. 20% - 45%: Linear decay from ~1.5x the bestPrice to the bestPrice\n// 3. 45% - 95%: Linear decay from the bestPrice to the worstPrice\n// 4. 95% - 100%: Constant at the worstPrice\n//\n// For a trade between 2 assets with 1% oracleError:\n// A 30-minute auction on a chain with a 12-second blocktime has a ~20% price drop per block\n// during the 1st period, ~0.8% during the 2nd period, and ~0.065% during the 3rd period.\n//\n// 30-minutes is the recommended length of auction for a chain with 12-second blocktimes.\n// 6 minutes, 7.5 minutes, 15 minutes, 1.5 minutes for each pariod respectively.\n//\n// Longer and shorter times can be used as well. The pricing method does not degrade\n// beyond the degree to which less overall blocktime means less overall precision.\n\nuint192 constant FIVE_PERCENT = 5e16; // {1} 0.05\nuint192 constant TWENTY_PERCENT = 20e16; // {1} 0.2\nuint192 constant TWENTY_FIVE_PERCENT = 25e16; // {1} 0.25\nuint192 constant FORTY_FIVE_PERCENT = 45e16; // {1} 0.45\nuint192 constant FIFTY_PERCENT = 50e16; // {1} 0.5\nuint192 constant NINETY_FIVE_PERCENT = 95e16; // {1} 0.95\n\nuint192 constant MAX_EXP = 6502287e18; // {1} (1000000/999999)^6502287 = ~666.6667\nuint192 constant BASE = 999999e12; // {1} (999999/1000000)\nuint192 constant ONE_POINT_FIVE = 150e16; // {1} 1.5\n\n/**\n * @title DutchTrade\n * @notice Implements a wholesale dutch auction via a 4-piecewise falling-price mechansim.\n * The overall idea is to handle 4 cases:\n * 1. Price manipulation of the exchange rate up to 1000x (eg: via a read-only reentrancy)\n * 2. Price movement of up to 50% during the auction\n * 3. Typical case: no significant price movement; clearing price within expected range\n * 4. No bots online; manual human doing bidding; additional time for tx clearing\n *\n * Case 1: Over the first 20% of the auction the price falls from ~1000x the best plausible\n * price down to 1.5x the best plausible price in a geometric series.\n * This period DOES NOT expect to receive a bid; it just defends against manipulated prices.\n * If a bid occurs during this period, a violation is reported to the Broker.\n * This is still safe for the protocol since other trades, with price discovery, can occur.\n *\n * Case 2: Over the next 20% of the auction the price falls from 1.5x the best plausible price\n * to the best plausible price, linearly. No violation is reported if a bid occurs. This case\n * exists to handle cases where prices change after the auction is started, naturally.\n *\n * Case 3: Over the next 50% of the auction the price falls from the best plausible price to the\n * worst price, linearly. The worst price is further discounted by the maxTradeSlippage.\n * This is the phase of the auction where bids will typically occur.\n *\n * Case 4: Lastly the price stays at the worst price for the final 5% of the auction to allow\n * a bid to occur if no bots are online and the only bidders are humans.\n *\n * To bid:\n * 1. Call `bidAmount()` view to check prices at various blocks.\n * 2. Provide approval of sell tokens for precisely the `bidAmount()` desired\n * 3. Wait until the desired block is reached (hopefully not in the first 20% of the auction)\n * 4. Call bid()\n */\ncontract DutchTrade is ITrade, Versioned {\n using FixLib for uint192;\n using SafeERC20 for IERC20Metadata;\n\n TradeKind public constant KIND = TradeKind.DUTCH_AUCTION;\n\n // solhint-disable-next-line var-name-mixedcase\n uint48 public immutable ONE_BLOCK; // {s} 1 block based on network\n\n BidType public bidType; // = BidType.NONE\n\n TradeStatus public status; // reentrancy protection\n\n IBroker public broker; // The Broker that cloned this contract into existence\n ITrading public origin; // the address that initialized the contract\n\n // === Auction ===\n IERC20Metadata public sell;\n IERC20Metadata public buy;\n uint192 public sellAmount; // {sellTok}\n\n // The auction runs from [startBlock, endTime], inclusive\n uint256 public startBlock; // {block} when the dutch auction begins (one block after init())\n uint256 public endBlock; // {block} when the dutch auction ends if no bids are received\n uint48 public endTime; // {s} not used in this contract; needed on interface\n\n uint192 public bestPrice; // {buyTok/sellTok} The best plausible price based on oracle data\n uint192 public worstPrice; // {buyTok/sellTok} The worst plausible price based on oracle data\n\n // === Bid ===\n address public bidder;\n // the bid amount is just whatever token balance is in the contract at settlement time\n\n // This modifier both enforces the state-machine pattern and guards against reentrancy.\n modifier stateTransition(TradeStatus begin, TradeStatus end) {\n require(status == begin, \"Invalid trade state\");\n status = TradeStatus.PENDING;\n _;\n assert(status == TradeStatus.PENDING);\n status = end;\n }\n\n // === Auction Sizing Views ===\n\n /// @return {qSellTok} The size of the lot being sold, in token quanta\n function lot() public view returns (uint256) {\n return sellAmount.shiftl_toUint(int8(sell.decimals()));\n }\n\n /// Calculates how much buy token is needed to purchase the lot at a particular block\n /// @param blockNumber {block} The block number of the bid\n /// @return {qBuyTok} The amount of buy tokens required to purchase the lot\n function bidAmount(uint256 blockNumber) external view returns (uint256) {\n return _bidAmount(_price(blockNumber));\n }\n\n // ==== Constructor ===\n\n constructor() {\n ONE_BLOCK = NetworkConfigLib.blocktime();\n\n status = TradeStatus.CLOSED;\n }\n\n // === External ===\n\n /// @param origin_ The Trader that originated the trade\n /// @param sell_ The asset being sold by the protocol\n /// @param buy_ The asset being bought by the protocol\n /// @param sellAmount_ {qSellTok} The amount to sell in the auction, in token quanta\n /// @param auctionLength {s} How many seconds the dutch auction should run for\n function init(\n ITrading origin_,\n IAsset sell_,\n IAsset buy_,\n uint256 sellAmount_,\n uint48 auctionLength,\n TradePrices memory prices\n ) external stateTransition(TradeStatus.NOT_STARTED, TradeStatus.OPEN) {\n assert(\n address(sell_) != address(0) &&\n address(buy_) != address(0) &&\n auctionLength >= 20 * ONE_BLOCK\n ); // misuse by caller\n\n // Only start dutch auctions under well-defined prices\n require(prices.sellLow != 0 && prices.sellHigh < FIX_MAX / 1000, \"bad sell pricing\");\n require(prices.buyLow != 0 && prices.buyHigh < FIX_MAX / 1000, \"bad buy pricing\");\n\n broker = IBroker(msg.sender);\n origin = origin_;\n sell = sell_.erc20();\n buy = buy_.erc20();\n\n require(sellAmount_ <= sell.balanceOf(address(this)), \"unfunded trade\");\n sellAmount = shiftl_toFix(sellAmount_, -int8(sell.decimals())); // {sellTok}\n\n uint256 _startBlock = block.number + 1; // start in the next block\n startBlock = _startBlock; // gas-saver\n\n uint256 _endBlock = _startBlock + auctionLength / ONE_BLOCK; // FLOOR; endBlock is inclusive\n endBlock = _endBlock; // gas-saver\n\n endTime = uint48(block.timestamp + ONE_BLOCK * (_endBlock - _startBlock + 1));\n\n // {buyTok/sellTok} = {UoA/sellTok} * {1} / {UoA/buyTok}\n uint192 _worstPrice = prices.sellLow.mulDiv(\n FIX_ONE - origin.maxTradeSlippage(),\n prices.buyHigh,\n FLOOR\n );\n uint192 _bestPrice = prices.sellHigh.div(prices.buyLow, CEIL); // no additional slippage\n assert(_worstPrice <= _bestPrice);\n worstPrice = _worstPrice; // gas-saver\n bestPrice = _bestPrice; // gas-saver\n }\n\n /// Bid for the auction lot at the current price; settle trade in protocol\n /// @dev Caller must have provided approval\n /// @return amountIn {qBuyTok} The quantity of tokens the bidder paid\n function bid() external returns (uint256 amountIn) {\n require(bidder == address(0), \"bid already received\");\n\n // {buyTok/sellTok}\n uint192 price = _price(block.number); // enforces auction ongoing\n\n // {qBuyTok}\n amountIn = _bidAmount(price);\n\n // Mark bidder\n bidder = msg.sender;\n bidType = BidType.TRANSFER;\n\n // status must begin OPEN\n assert(status == TradeStatus.OPEN);\n\n // reportViolation if auction cleared in geometric phase\n if (price > bestPrice.mul(ONE_POINT_FIVE, CEIL)) {\n broker.reportViolation();\n }\n\n // Transfer in buy tokens from bidder\n buy.safeTransferFrom(msg.sender, address(this), amountIn);\n\n // settle() in core protocol\n origin.settleTrade(sell);\n\n // confirm .settleTrade() succeeded and .settle() has been called\n assert(status == TradeStatus.CLOSED);\n }\n\n /// Bid with callback for the auction lot at the current price; settle trade in protocol\n /// Sold funds are sent back to the callee first via callee.dutchTradeCallback(...)\n /// Balance of buy token must increase by bidAmount(current block) after callback\n ///\n /// @dev Caller must implement IDutchTradeCallee\n /// @param data {bytes} The data to pass to the callback\n /// @return amountIn {qBuyTok} The quantity of tokens the bidder paid\n function bidWithCallback(bytes calldata data) external returns (uint256 amountIn) {\n require(bidder == address(0), \"bid already received\");\n\n // {buyTok/sellTok}\n uint192 price = _price(block.number); // enforces auction ongoing\n\n // {qBuyTok}\n amountIn = _bidAmount(price);\n\n // Mark bidder\n bidder = msg.sender;\n bidType = BidType.CALLBACK;\n\n // status must begin OPEN\n assert(status == TradeStatus.OPEN);\n\n // reportViolation if auction cleared in geometric phase\n if (price > bestPrice.mul(ONE_POINT_FIVE, CEIL)) {\n broker.reportViolation();\n }\n\n // Transfer sell tokens to bidder\n sell.safeTransfer(bidder, lot()); // {qSellTok}\n\n uint256 balanceBefore = buy.balanceOf(address(this)); // {qBuyTok}\n IDutchTradeCallee(bidder).dutchTradeCallback(address(buy), amountIn, data);\n require(\n amountIn <= buy.balanceOf(address(this)) - balanceBefore,\n \"insufficient buy tokens\"\n );\n\n // settle() in core protocol\n origin.settleTrade(sell);\n\n // confirm .settleTrade() succeeded and .settle() has been called\n assert(status == TradeStatus.CLOSED);\n }\n\n /// Settle the auction, emptying the contract of balances\n /// @return soldAmt {qSellTok} Token quantity sold by the protocol\n /// @return boughtAmt {qBuyTok} Token quantity purchased by the protocol\n function settle()\n external\n stateTransition(TradeStatus.OPEN, TradeStatus.CLOSED)\n returns (uint256 soldAmt, uint256 boughtAmt)\n {\n require(msg.sender == address(origin), \"only origin can settle\");\n require(bidder != address(0) || block.number > endBlock, \"auction not over\");\n\n if (bidType == BidType.CALLBACK) {\n soldAmt = lot(); // {qSellTok}\n } else if (bidType == BidType.TRANSFER) {\n soldAmt = lot(); // {qSellTok}\n sell.safeTransfer(bidder, soldAmt); // {qSellTok}\n }\n\n // Transfer remaining balances back to origin\n boughtAmt = buy.balanceOf(address(this)); // {qBuyTok}\n buy.safeTransfer(address(origin), boughtAmt); // {qBuyTok}\n sell.safeTransfer(address(origin), sell.balanceOf(address(this))); // {qSellTok}\n }\n\n /// Anyone can transfer any ERC20 back to the origin after the trade has been closed\n /// @dev Escape hatch in case of accidentally transferred tokens after auction end\n /// @custom:interaction CEI (and respects the state lock)\n function transferToOriginAfterTradeComplete(IERC20Metadata erc20) external {\n require(status == TradeStatus.CLOSED, \"only after trade is closed\");\n erc20.safeTransfer(address(origin), erc20.balanceOf(address(this)));\n }\n\n /// @return true iff the trade can be settled.\n // Guaranteed to be true some time after init(), until settle() is called\n function canSettle() external view returns (bool) {\n return status == TradeStatus.OPEN && (bidder != address(0) || block.number > endBlock);\n }\n\n // === Private ===\n\n /// Return the price of the auction at a particular timestamp\n /// @param blockNumber {block} The block number to get price for\n /// @return {buyTok/sellTok}\n function _price(uint256 blockNumber) private view returns (uint192) {\n uint256 _startBlock = startBlock; // gas savings\n uint256 _endBlock = endBlock; // gas savings\n require(blockNumber >= _startBlock, \"auction not started\");\n require(blockNumber <= _endBlock, \"auction over\");\n\n /// Price Curve:\n /// - first 20%: geometrically decrease the price from 1000x the bestPrice to 1.5x it\n /// - next 25%: linearly decrease the price from 1.5x the bestPrice to 1x it\n /// - next 50%: linearly decrease the price from bestPrice to worstPrice\n /// - last 5%: constant at worstPrice\n\n uint192 progression = divuu(blockNumber - _startBlock, _endBlock - _startBlock); // {1}\n\n // Fast geometric decay -- 0%-20% of auction\n if (progression < TWENTY_PERCENT) {\n uint192 exp = MAX_EXP.mulDiv(TWENTY_PERCENT - progression, TWENTY_PERCENT, ROUND);\n\n // bestPrice * ((1000000/999999) ^ exp) = bestPrice / ((999999/1000000) ^ exp)\n // safe uint48 downcast: exp is at-most 6502287\n // {buyTok/sellTok} = {buyTok/sellTok} / {1} ^ {1}\n return bestPrice.mulDiv(ONE_POINT_FIVE, BASE.powu(uint48(exp.toUint(ROUND))), CEIL);\n // this reverts for bestPrice >= 6.21654046e36 * FIX_ONE\n } else if (progression < FORTY_FIVE_PERCENT) {\n // First linear decay -- 20%-45% of auction\n // 1.5x -> 1x the bestPrice\n\n uint192 _bestPrice = bestPrice; // gas savings\n // {buyTok/sellTok} = {buyTok/sellTok} * {1}\n uint192 highPrice = _bestPrice.mul(ONE_POINT_FIVE, CEIL);\n return\n highPrice -\n (highPrice - _bestPrice).mulDiv(progression - TWENTY_PERCENT, TWENTY_FIVE_PERCENT);\n } else if (progression < NINETY_FIVE_PERCENT) {\n // Second linear decay -- 45%-95% of auction\n // bestPrice -> worstPrice\n\n uint192 _bestPrice = bestPrice; // gas savings\n // {buyTok/sellTok} = {buyTok/sellTok} * {1}\n return\n _bestPrice -\n (_bestPrice - worstPrice).mulDiv(progression - FORTY_FIVE_PERCENT, FIFTY_PERCENT);\n }\n\n // Constant price -- 95%-100% of auction\n return worstPrice;\n }\n\n /// Calculates how much buy token is needed to purchase the lot at a particular price\n /// @param price {buyTok/sellTok}\n /// @return {qBuyTok} The amount of buy tokens required to purchase the lot\n function _bidAmount(uint192 price) public view returns (uint256) {\n // {qBuyTok} = {sellTok} * {buyTok/sellTok} * {qBuyTok/buyTok}\n return sellAmount.mul(price, CEIL).shiftl_toUint(int8(buy.decimals()), CEIL);\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,499,900 |
a87aecc665dcc9e83918d74aad64dbfa6f601b3cd6b7bcd9459fc936c4ac1eb0
|
b0844633b604ac9c5e676cf240c84879caf649b043c920dd32e6d7b0c7377ade
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
962e288cda161bafc29d5d8e8dfaa7f2cf3252a1
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,499,902 |
a982896f2dc35eb0ed3a892dcccfe07733cecf74b98aa423d01ddbd42eb6059c
|
d80aff6f2b75a7af46802227fac6cffa78ba6c4225d5cfbb4292c9edf00ccabc
|
578f533873dc8ea60ab1417180cc531f172ee292
|
29ef46035e9fa3d570c598d3266424ca11413b0c
|
78448860f92a8bc1cdea327167fa92d7f1e647a7
|
3d602d80600a3d3981f3363d3d373d3d3d363d735397d0869aba0d55e96d5716d383f6e1d8695ed75af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d735397d0869aba0d55e96d5716d383f6e1d8695ed75af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/Forwarder.sol": {
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.10;\nimport '@openzeppelin/contracts/token/ERC1155/IERC1155.sol';\nimport '@openzeppelin/contracts/token/ERC721/IERC721.sol';\nimport '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';\nimport '@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol';\nimport './ERC20Interface.sol';\nimport './TransferHelper.sol';\nimport './IForwarder.sol';\n\n/**\n * Contract that will forward any incoming Ether to the creator of the contract\n *\n */\ncontract Forwarder is IERC721Receiver, ERC1155Receiver, IForwarder {\n // Address to which any funds sent to this contract will be forwarded\n address public parentAddress;\n bool public autoFlush721 = true;\n bool public autoFlush1155 = true;\n\n event ForwarderDeposited(address from, uint256 value, bytes data);\n\n /**\n * Initialize the contract, and sets the destination address to that of the creator\n */\n function init(\n address _parentAddress,\n bool _autoFlush721,\n bool _autoFlush1155\n ) external onlyUninitialized {\n parentAddress = _parentAddress;\n uint256 value = address(this).balance;\n\n // set whether we want to automatically flush erc721/erc1155 tokens or not\n autoFlush721 = _autoFlush721;\n autoFlush1155 = _autoFlush1155;\n\n if (value == 0) {\n return;\n }\n\n (bool success, ) = parentAddress.call{ value: value }('');\n require(success, 'Flush failed');\n\n // NOTE: since we are forwarding on initialization,\n // we don't have the context of the original sender.\n // We still emit an event about the forwarding but set\n // the sender to the forwarder itself\n emit ForwarderDeposited(address(this), value, msg.data);\n }\n\n /**\n * Modifier that will execute internal code block only if the sender is the parent address\n */\n modifier onlyParent {\n require(msg.sender == parentAddress, 'Only Parent');\n _;\n }\n\n /**\n * Modifier that will execute internal code block only if the contract has not been initialized yet\n */\n modifier onlyUninitialized {\n require(parentAddress == address(0x0), 'Already initialized');\n _;\n }\n\n /**\n * Default function; Gets called when data is sent but does not match any other function\n */\n fallback() external payable {\n flush();\n }\n\n /**\n * Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address\n */\n receive() external payable {\n flush();\n }\n\n /**\n * @inheritdoc IForwarder\n */\n function setAutoFlush721(bool autoFlush)\n external\n virtual\n override\n onlyParent\n {\n autoFlush721 = autoFlush;\n }\n\n /**\n * @inheritdoc IForwarder\n */\n function setAutoFlush1155(bool autoFlush)\n external\n virtual\n override\n onlyParent\n {\n autoFlush1155 = autoFlush;\n }\n\n /**\n * ERC721 standard callback function for when a ERC721 is transfered. The forwarder will send the nft\n * to the base wallet once the nft contract invokes this method after transfering the nft.\n *\n * @param _operator The address which called `safeTransferFrom` function\n * @param _from The address of the sender\n * @param _tokenId The token id of the nft\n * @param data Additional data with no specified format, sent in call to `_to`\n */\n function onERC721Received(\n address _operator,\n address _from,\n uint256 _tokenId,\n bytes memory data\n ) external virtual override returns (bytes4) {\n if (autoFlush721) {\n IERC721 instance = IERC721(msg.sender);\n require(\n instance.supportsInterface(type(IERC721).interfaceId),\n 'The caller does not support the ERC721 interface'\n );\n // this won't work for ERC721 re-entrancy\n instance.safeTransferFrom(address(this), parentAddress, _tokenId, data);\n }\n\n return this.onERC721Received.selector;\n }\n\n function callFromParent(\n address target,\n uint256 value,\n bytes calldata data\n ) external onlyParent returns (bytes memory) {\n (bool success, bytes memory returnedData) = target.call{ value: value }(\n data\n );\n require(success, 'Parent call execution failed');\n\n return returnedData;\n }\n\n /**\n * @inheritdoc IERC1155Receiver\n */\n function onERC1155Received(\n address _operator,\n address _from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external virtual override returns (bytes4) {\n IERC1155 instance = IERC1155(msg.sender);\n require(\n instance.supportsInterface(type(IERC1155).interfaceId),\n 'The caller does not support the IERC1155 interface'\n );\n\n if (autoFlush1155) {\n instance.safeTransferFrom(address(this), parentAddress, id, value, data);\n }\n\n return this.onERC1155Received.selector;\n }\n\n /**\n * @inheritdoc IERC1155Receiver\n */\n function onERC1155BatchReceived(\n address _operator,\n address _from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external virtual override returns (bytes4) {\n IERC1155 instance = IERC1155(msg.sender);\n require(\n instance.supportsInterface(type(IERC1155).interfaceId),\n 'The caller does not support the IERC1155 interface'\n );\n\n if (autoFlush1155) {\n instance.safeBatchTransferFrom(\n address(this),\n parentAddress,\n ids,\n values,\n data\n );\n }\n\n return this.onERC1155BatchReceived.selector;\n }\n\n /**\n * @inheritdoc IForwarder\n */\n function flushTokens(address tokenContractAddress)\n external\n virtual\n override\n onlyParent\n {\n ERC20Interface instance = ERC20Interface(tokenContractAddress);\n address forwarderAddress = address(this);\n uint256 forwarderBalance = instance.balanceOf(forwarderAddress);\n if (forwarderBalance == 0) {\n return;\n }\n\n TransferHelper.safeTransfer(\n tokenContractAddress,\n parentAddress,\n forwarderBalance\n );\n }\n\n /**\n * @inheritdoc IForwarder\n */\n function flushERC721Token(address tokenContractAddress, uint256 tokenId)\n external\n virtual\n override\n onlyParent\n {\n IERC721 instance = IERC721(tokenContractAddress);\n require(\n instance.supportsInterface(type(IERC721).interfaceId),\n 'The tokenContractAddress does not support the ERC721 interface'\n );\n\n address ownerAddress = instance.ownerOf(tokenId);\n instance.transferFrom(ownerAddress, parentAddress, tokenId);\n }\n\n /**\n * @inheritdoc IForwarder\n */\n function flushERC1155Tokens(address tokenContractAddress, uint256 tokenId)\n external\n virtual\n override\n onlyParent\n {\n IERC1155 instance = IERC1155(tokenContractAddress);\n require(\n instance.supportsInterface(type(IERC1155).interfaceId),\n 'The caller does not support the IERC1155 interface'\n );\n\n address forwarderAddress = address(this);\n uint256 forwarderBalance = instance.balanceOf(forwarderAddress, tokenId);\n\n instance.safeTransferFrom(\n forwarderAddress,\n parentAddress,\n tokenId,\n forwarderBalance,\n ''\n );\n }\n\n /**\n * @inheritdoc IForwarder\n */\n function batchFlushERC1155Tokens(\n address tokenContractAddress,\n uint256[] calldata tokenIds\n ) external virtual override onlyParent {\n IERC1155 instance = IERC1155(tokenContractAddress);\n require(\n instance.supportsInterface(type(IERC1155).interfaceId),\n 'The caller does not support the IERC1155 interface'\n );\n\n address forwarderAddress = address(this);\n uint256[] memory amounts = new uint256[](tokenIds.length);\n for (uint256 i = 0; i < tokenIds.length; i++) {\n amounts[i] = instance.balanceOf(forwarderAddress, tokenIds[i]);\n }\n\n instance.safeBatchTransferFrom(\n forwarderAddress,\n parentAddress,\n tokenIds,\n amounts,\n ''\n );\n }\n\n /**\n * Flush the entire balance of the contract to the parent address.\n */\n function flush() public {\n uint256 value = address(this).balance;\n\n if (value == 0) {\n return;\n }\n\n (bool success, ) = parentAddress.call{ value: value }('');\n require(success, 'Flush failed');\n emit ForwarderDeposited(msg.sender, value, msg.data);\n }\n\n /**\n * @inheritdoc IERC165\n */\n function supportsInterface(bytes4 interfaceId)\n public\n virtual\n override(ERC1155Receiver, IERC165)\n view\n returns (bool)\n {\n return\n interfaceId == type(IForwarder).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC1155/IERC1155.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155 is IERC165 {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC1155Receiver.sol\";\nimport \"../../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\nabstract contract ERC1155Receiver is ERC165, IERC1155Receiver {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);\n }\n}\n"
},
"contracts/ERC20Interface.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.10;\n\n/**\n * Contract that exposes the needed erc20 token functions\n */\n\nabstract contract ERC20Interface {\n // Send _value amount of tokens to address _to\n function transfer(address _to, uint256 _value)\n public\n virtual\n returns (bool success);\n\n // Get the account balance of another account with address _owner\n function balanceOf(address _owner)\n public\n virtual\n view\n returns (uint256 balance);\n}\n"
},
"contracts/TransferHelper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// source: https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/TransferHelper.sol\npragma solidity 0.8.10;\n\nimport '@openzeppelin/contracts/utils/Address.sol';\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes('transfer(address,uint256)')));\n (bool success, bytes memory data) = token.call(\n abi.encodeWithSelector(0xa9059cbb, to, value)\n );\n require(\n success && (data.length == 0 || abi.decode(data, (bool))),\n 'TransferHelper::safeTransfer: transfer failed'\n );\n }\n\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));\n (bool success, bytes memory returndata) = token.call(\n abi.encodeWithSelector(0x23b872dd, from, to, value)\n );\n Address.verifyCallResult(\n success,\n returndata,\n 'TransferHelper::transferFrom: transferFrom failed'\n );\n }\n}\n"
},
"contracts/IForwarder.sol": {
"content": "pragma solidity ^0.8.0;\n\nimport '@openzeppelin/contracts/utils/introspection/IERC165.sol';\n\ninterface IForwarder is IERC165 {\n /**\n * Sets the autoflush721 parameter.\n *\n * @param autoFlush whether to autoflush erc721 tokens\n */\n function setAutoFlush721(bool autoFlush) external;\n\n /**\n * Sets the autoflush1155 parameter.\n *\n * @param autoFlush whether to autoflush erc1155 tokens\n */\n function setAutoFlush1155(bool autoFlush) external;\n\n /**\n * Execute a token transfer of the full balance from the forwarder token to the parent address\n *\n * @param tokenContractAddress the address of the erc20 token contract\n */\n function flushTokens(address tokenContractAddress) external;\n\n /**\n * Execute a nft transfer from the forwarder to the parent address\n *\n * @param tokenContractAddress the address of the ERC721 NFT contract\n * @param tokenId The token id of the nft\n */\n function flushERC721Token(address tokenContractAddress, uint256 tokenId)\n external;\n\n /**\n * Execute a nft transfer from the forwarder to the parent address.\n *\n * @param tokenContractAddress the address of the ERC1155 NFT contract\n * @param tokenId The token id of the nft\n */\n function flushERC1155Tokens(address tokenContractAddress, uint256 tokenId)\n external;\n\n /**\n * Execute a batch nft transfer from the forwarder to the parent address.\n *\n * @param tokenContractAddress the address of the ERC1155 NFT contract\n * @param tokenIds The token ids of the nfts\n */\n function batchFlushERC1155Tokens(\n address tokenContractAddress,\n uint256[] calldata tokenIds\n ) external;\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n @dev Handles the receipt of a single ERC1155 token type. This function is\n called at the end of a `safeTransferFrom` after the balance has been updated.\n To accept the transfer, this must return\n `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n (i.e. 0xf23a6e61, or its own function selector).\n @param operator The address which initiated the transfer (i.e. msg.sender)\n @param from The address which previously owned the token\n @param id The ID of the token being transferred\n @param value The amount of tokens being transferred\n @param data Additional data with no specified format\n @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n @dev Handles the receipt of a multiple ERC1155 token types. This function\n is called at the end of a `safeBatchTransferFrom` after the balances have\n been updated. To accept the transfer(s), this must return\n `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n (i.e. 0xbc197c81, or its own function selector).\n @param operator The address which initiated the batch transfer (i.e. msg.sender)\n @param from The address which previously owned the token\n @param ids An array containing ids of each token being transferred (order and length must match values array)\n @param values An array containing amounts of each token being transferred (order and length must match ids array)\n @param data Additional data with no specified format\n @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": false,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,499,903 |
dcf7155c21a44e95afce8286dadf91e6a2b13a5008c5c8802460cf72fa17b2d1
|
3f17674ec62764e595b4047b94b2abdb3852eacb8114f3610abfc6fd82fac9e7
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
49f9fad0457d9cfc505c1ab31791e7bd6a052c69
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,499,904 |
ac466f914db45f340c9faac1430f902ea8618bd620f29223fe22262ceeaccc2a
|
80e432d130cf5192dddeaad7959b63aaf08e26d090e9191cd54fe41e317ec4ff
|
b3f9f4c0fb15128f87f570c770dcdd59fd37f124
|
b3f9f4c0fb15128f87f570c770dcdd59fd37f124
|
ac67033766f3549f4d96e2ade27791471c3ff374
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f623d7c7f0e930d8963184340038f9af9ceb8d8c0086007557f6e75382374384e10a7b62f6258695b72d88efc120a7f2e072a8611889b2c2b0c6008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103648061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030b565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b600060208284031215610304578081fd5b5035919050565b60008282101561032957634e487b7160e01b81526011600452602481fd5b50039056fea2646970667358221220b1e7b3b67d6b13f71c8894d4682cebb6308fd2fa14ed2a3227c63fd43571d85764736f6c63430008040033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030b565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b600060208284031215610304578081fd5b5035919050565b60008282101561032957634e487b7160e01b81526011600452602481fd5b50039056fea2646970667358221220b1e7b3b67d6b13f71c8894d4682cebb6308fd2fa14ed2a3227c63fd43571d85764736f6c63430008040033
| |
1 | 19,499,911 |
102d741fb4a07413abbad615dd2eb8955b641a7c6e7d46568e18ce8e2b852cd6
|
18cbd55a0b47e2073b8e7bfc421f79a0829d9c8b87de3592f08f4675332774c5
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
1ee5684eb1d8d36d40dd4411673179774cde6b53
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,499,914 |
bdac1dea20b3f6e314cad5d4ac5dd1329ebc1fa1836285215ab49716d021bbc5
|
898233098ce7b310c925ed93a0d3feec1b9862b04cfcbe2e907d8d37c6c9265c
|
db76311bb46e06833d534930e9e4539a0a134fa7
|
db76311bb46e06833d534930e9e4539a0a134fa7
|
dcca8fc366489a5f8908f3935dcfa08ff8ca0b54
|
608060405234801561001057600080fd5b506040516109383803806109388339818101604052604081101561003357600080fd5b810190808051604051939291908464010000000082111561005357600080fd5b8382019150602082018581111561006957600080fd5b825186600182028301116401000000008211171561008657600080fd5b8083526020830192505050908051906020019080838360005b838110156100ba57808201518184015260208101905061009f565b50505050905090810190601f1680156100e75780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561010a57600080fd5b8382019150602082018581111561012057600080fd5b825186600182028301116401000000008211171561013d57600080fd5b8083526020830192505050908051906020019080838360005b83811015610171578082015181840152602081019050610156565b50505050905090810190601f16801561019e5780820380516001836020036101000a031916815260200191505b5060405250505081600090805190602001906101bb929190610243565b5080600190805190602001906101d2929190610243565b506040516101df906102c3565b604051809103906000f0801580156101fb573d6000803e3d6000fd5b50600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050506102f4565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061028457805160ff19168380011785556102b2565b828001600101855582156102b2579182015b828111156102b1578251825591602001919060010190610296565b5b5090506102bf91906102cf565b5090565b60fa8061083e83390190565b6102f191905b808211156102ed5760008160009055506001016102d5565b5090565b90565b61053b806103036000396000f3fe60806040526004361061004e5760003560e01c80631b55ba3a1461005a5780634fe6f55f1461006457806370e44c6a146100f45780638da5cb5b146100fe578063bedf0f4a1461018e57610055565b3661005557005b600080fd5b610062610198565b005b34801561007057600080fd5b506100796103c5565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b957808201518184015260208101905061009e565b50505050905090810190601f1680156100e65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100fc610463565b005b34801561010a57600080fd5b50610113610465565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610153578082015181840152602081019050610138565b50505050905090810190601f1680156101805780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610196610503565b005b600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663feae9ad36040518163ffffffff1660e01b815260040160206040518083038186803b15801561027057600080fd5b505afa158015610284573d6000803e3d6000fd5b505050506040513d602081101561029a57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f193505050501580156102f0573d6000803e3d6000fd5b50600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050565b60018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561045b5780601f106104305761010080835404028352916020019161045b565b820191906000526020600020905b81548152906001019060200180831161043e57829003601f168201915b505050505081565b565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104fb5780601f106104d0576101008083540402835291602001916104fb565b820191906000526020600020905b8154815290600101906020018083116104de57829003601f168201915b505050505081565b56fea26469706673582212200f005273c59eb01e2ac4044533bed1876e646bc1cc8d2dc69c1863046073b2c064736f6c63430006060033608060405234801561001057600080fd5b5060db8061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c0f93a1146037578063feae9ad314603f575b600080fd5b603d6087565b005b60456089565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b565b6000732c70a269380fac2bc22a218aaf822ebe603fb5c990509056fea264697066735822122023613d1a49b08f1719aa0b76eff883719f201eef2591468fbe4ca1ae4e96466364736f6c63430006060033000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a30784442373633313142623436653036383333643533343933306539653435333961306131333446613700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002a30786441433137463935384432656535323361323230363230363939343539374331334438333165633700000000000000000000000000000000000000000000
|
60806040526004361061004e5760003560e01c80631b55ba3a1461005a5780634fe6f55f1461006457806370e44c6a146100f45780638da5cb5b146100fe578063bedf0f4a1461018e57610055565b3661005557005b600080fd5b610062610198565b005b34801561007057600080fd5b506100796103c5565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b957808201518184015260208101905061009e565b50505050905090810190601f1680156100e65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100fc610463565b005b34801561010a57600080fd5b50610113610465565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610153578082015181840152602081019050610138565b50505050905090810190601f1680156101805780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610196610503565b005b600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663feae9ad36040518163ffffffff1660e01b815260040160206040518083038186803b15801561027057600080fd5b505afa158015610284573d6000803e3d6000fd5b505050506040513d602081101561029a57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f193505050501580156102f0573d6000803e3d6000fd5b50600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050565b60018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561045b5780601f106104305761010080835404028352916020019161045b565b820191906000526020600020905b81548152906001019060200180831161043e57829003601f168201915b505050505081565b565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104fb5780601f106104d0576101008083540402835291602001916104fb565b820191906000526020600020905b8154815290600101906020018083116104de57829003601f168201915b505050505081565b56fea26469706673582212200f005273c59eb01e2ac4044533bed1876e646bc1cc8d2dc69c1863046073b2c064736f6c63430006060033
| |
1 | 19,499,914 |
bdac1dea20b3f6e314cad5d4ac5dd1329ebc1fa1836285215ab49716d021bbc5
|
898233098ce7b310c925ed93a0d3feec1b9862b04cfcbe2e907d8d37c6c9265c
|
db76311bb46e06833d534930e9e4539a0a134fa7
|
dcca8fc366489a5f8908f3935dcfa08ff8ca0b54
|
a7b4ff736db2e0d062bb462c9a099d05d40fff4e
|
608060405234801561001057600080fd5b5060db8061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c0f93a1146037578063feae9ad314603f575b600080fd5b603d6087565b005b60456089565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b565b6000732c70a269380fac2bc22a218aaf822ebe603fb5c990509056fea264697066735822122023613d1a49b08f1719aa0b76eff883719f201eef2591468fbe4ca1ae4e96466364736f6c63430006060033
|
6080604052348015600f57600080fd5b506004361060325760003560e01c80630c0f93a1146037578063feae9ad314603f575b600080fd5b603d6087565b005b60456089565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b565b6000732c70a269380fac2bc22a218aaf822ebe603fb5c990509056fea264697066735822122023613d1a49b08f1719aa0b76eff883719f201eef2591468fbe4ca1ae4e96466364736f6c63430006060033
| |
1 | 19,499,917 |
78833f509da6a64e85e9cfc36e237828d9bd1b26aeb10dd0e070f49386ef406b
|
0304672d41e1303459a44d4be6d7b46ba09fa0d21642124c168b7824cd9d1cc8
|
215bdff23dd182c902533b4ad921ff16c3bd40cc
|
215bdff23dd182c902533b4ad921ff16c3bd40cc
|
9385934f026d10c068d475e7058733251ed6791e
|
6101006040526a084595161401484a0000006006553480156200002157600080fd5b50600080546001600160a01b031916339081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a350737a250d5630b4cf539739df2c5dacb4c659f2488d6080819052604080516315ab88c960e31b8152905163ad5c4648916004808201926020929091908290030181865afa158015620000b9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000df919062000330565b6001600160a01b0390811660c052601960025560286003556080516040805163c45a015560e01b81529051919092169163c45a01559160048083019260209291908290030181865afa1580156200013a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000160919062000330565b60c0516040516364e329cb60e11b81523060048201526001600160a01b03918216602482015291169063c9c65396906044016020604051808303816000875af1158015620001b2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001d8919062000330565b6001600160a01b0390811660a05273215bdff23dd182c902533b4ad921ff16c3bd40cc60e0523360008181526007602090815260408083206b033b2e3c9fd0803ce80000009055600982527f0e2935ac12d643410a85e89a52141649acea0eb37fe46d486af92614ca7f06cd8054600160ff19918216811790925582852080548216831790553085528285208054909116909117905560088083528184206080519096168085529583528184206000199081905594845282528083209483529381528382208390557f833eb271b1113e1a00ee1adec85b2effeac2ed7a693bad56c3774e1607dcdc9890529190912055620002d03390565b6001600160a01b031660006001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6b033b2e3c9fd0803ce80000006040516200032291815260200190565b60405180910390a362000362565b6000602082840312156200034357600080fd5b81516001600160a01b03811681146200035b57600080fd5b9392505050565b60805160a05160c05160e05161105d620003a36000396000610b0701526000610a7a015260008181610944015261098601526000610ad1015261105d6000f3fe6080604052600436106101185760003560e01c80638c0b5e22116100a0578063c9567bf911610064578063c9567bf914610324578063cc1776d314610339578063dba9d4201461034f578063dd62ed3e1461036f578063f2fde38b146103b557600080fd5b80638c0b5e22146102795780638da5cb5b1461028f5780639036ed4d146102b757806395d89b41146102d7578063a9059cbb1461030457600080fd5b8063313ce567116100e7578063313ce567146101e55780634f7041a51461020157806370a0823114610217578063715018a61461024d578063751039fc1461026457600080fd5b806306fdde0314610124578063095ea7b31461016c57806318160ddd1461019c57806323b872dd146101c557600080fd5b3661011f57005b600080fd5b34801561013057600080fd5b5060408051808201909152600d81526c4469676974616c5477696e414960981b60208201525b6040516101639190610daf565b60405180910390f35b34801561017857600080fd5b5061018c610187366004610e19565b6103d5565b6040519015158152602001610163565b3480156101a857600080fd5b506b033b2e3c9fd0803ce80000005b604051908152602001610163565b3480156101d157600080fd5b5061018c6101e0366004610e43565b6103ec565b3480156101f157600080fd5b5060405160128152602001610163565b34801561020d57600080fd5b506101b760025481565b34801561022357600080fd5b506101b7610232366004610e7f565b6001600160a01b031660009081526007602052604090205490565b34801561025957600080fd5b5061026261043e565b005b34801561027057600080fd5b506102626104bb565b34801561028557600080fd5b506101b760065481565b34801561029b57600080fd5b506000546040516001600160a01b039091168152602001610163565b3480156102c357600080fd5b506102626102d2366004610ea1565b6104f7565b3480156102e357600080fd5b506040805180820190915260048152634454414960e01b6020820152610156565b34801561031057600080fd5b5061018c61031f366004610e19565b61052c565b34801561033057600080fd5b50610262610539565b34801561034557600080fd5b506101b760035481565b34801561035b57600080fd5b5061026261036a366004610e7f565b610576565b34801561037b57600080fd5b506101b761038a366004610ec3565b6001600160a01b03918216600090815260086020908152604080832093909416825291909152205490565b3480156103c157600080fd5b506102626103d0366004610e7f565b6105c4565b60006103e23384846105fa565b5060015b92915050565b60006103f984848461071e565b6001600160a01b03841660009081526008602090815260408083203380855292529091205461043491869161042f908690610f0c565b6105fa565b5060019392505050565b6000546001600160a01b031633146104715760405162461bcd60e51b815260040161046890610f1f565b60405180910390fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031633146104e55760405162461bcd60e51b815260040161046890610f1f565b6b033b2e3c9fd0803ce8000000600655565b6000546001600160a01b031633146105215760405162461bcd60e51b815260040161046890610f1f565b600291909155600355565b60006103e233848461071e565b6000546001600160a01b031633146105635760405162461bcd60e51b815260040161046890610f1f565b6004805460ff1916600117905543600555565b6000546001600160a01b031633146105a05760405162461bcd60e51b815260040161046890610f1f565b6001600160a01b03166000908152600960205260409020805460ff19166001179055565b6000546001600160a01b031633146105ee5760405162461bcd60e51b815260040161046890610f1f565b6105f781610cef565b50565b6001600160a01b03831661065c5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610468565b6001600160a01b0382166106bd5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610468565b6001600160a01b0383811660008181526008602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166107825760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610468565b633b9aca0081116107c85760405162461bcd60e51b815260206004820152601060248201526f135a5b881d1c985b9cd9995c88185b5d60821b6044820152606401610468565b6001600160a01b03831660009081526009602052604081205460ff168061080757506001600160a01b03831660009081526009602052604090205460ff165b1561081457506000610b7e565b60045460ff161580159061082a57506006548211155b6108815760405162461bcd60e51b815260206004820152602260248201527f4c61756e6368202f204d6178205478416d6f756e74203225206174206c61756e6044820152610c6d60f31b6064820152608401610468565b600454610100900460ff16600103610942576001600160a01b038416600090815260076020526040812080548492906108bb908490610f0c565b90915550506001600160a01b038316600090815260076020526040812080548492906108e8908490610f54565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161093491815260200190565b60405180910390a350505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316846001600160a01b0316036109845750600254610b7e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316836001600160a01b031603610b7a57306000908152600760205260409020546934f086f3b33b68400000811180156109ee5750600454610100900460ff16155b15610b70576a084595161401484a000000811115610a1457506a084595161401484a0000005b6004805461ff0019166101001790556040805160028082526060820183526000926020830190803683370190505090503081600081518110610a5857610a58610f67565b60200260200101906001600160a01b031690816001600160a01b0316815250507f000000000000000000000000000000000000000000000000000000000000000081600181518110610aac57610aac610f67565b6001600160a01b03928316602091820292909201015260405163791ac94760e01b81527f00000000000000000000000000000000000000000000000000000000000000009091169063791ac94790610b3190859060009086907f0000000000000000000000000000000000000000000000000000000000000000904290600401610f7d565b600060405180830381600087803b158015610b4b57600080fd5b505af1158015610b5f573d6000803e3d6000fd5b50506004805461ff00191690555050505b5050600354610b7e565b5060005b8015610cc15760006064610b928385610fee565b610b9c9190611005565b90506000610baa8285610f0c565b6001600160a01b038716600090815260076020526040812080549293508692909190610bd7908490610f0c565b90915550506001600160a01b03851660009081526007602052604081208054839290610c04908490610f54565b90915550503060009081526007602052604081208054849290610c28908490610f54565b909155505060405182815230906001600160a01b038816907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3846001600160a01b0316866001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610cb291815260200190565b60405180910390a35050610ce9565b6001600160a01b038416600090815260076020526040812080548492906108bb908490610f0c565b50505050565b6001600160a01b038116610d545760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610468565b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b600060208083528351808285015260005b81811015610ddc57858101830151858201604001528201610dc0565b506000604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b0381168114610e1457600080fd5b919050565b60008060408385031215610e2c57600080fd5b610e3583610dfd565b946020939093013593505050565b600080600060608486031215610e5857600080fd5b610e6184610dfd565b9250610e6f60208501610dfd565b9150604084013590509250925092565b600060208284031215610e9157600080fd5b610e9a82610dfd565b9392505050565b60008060408385031215610eb457600080fd5b50508035926020909101359150565b60008060408385031215610ed657600080fd5b610edf83610dfd565b9150610eed60208401610dfd565b90509250929050565b634e487b7160e01b600052601160045260246000fd5b818103818111156103e6576103e6610ef6565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b808201808211156103e6576103e6610ef6565b634e487b7160e01b600052603260045260246000fd5b600060a082018783526020878185015260a0604085015281875180845260c086019150828901935060005b81811015610fcd5784516001600160a01b031683529383019391830191600101610fa8565b50506001600160a01b03969096166060850152505050608001529392505050565b80820281158282048414176103e6576103e6610ef6565b60008261102257634e487b7160e01b600052601260045260246000fd5b50049056fea2646970667358221220825532ab61c5b2734d6bd5994ccb86717030d8ade1366ff1af1ce2038dafa36364736f6c63430008120033
|
6080604052600436106101185760003560e01c80638c0b5e22116100a0578063c9567bf911610064578063c9567bf914610324578063cc1776d314610339578063dba9d4201461034f578063dd62ed3e1461036f578063f2fde38b146103b557600080fd5b80638c0b5e22146102795780638da5cb5b1461028f5780639036ed4d146102b757806395d89b41146102d7578063a9059cbb1461030457600080fd5b8063313ce567116100e7578063313ce567146101e55780634f7041a51461020157806370a0823114610217578063715018a61461024d578063751039fc1461026457600080fd5b806306fdde0314610124578063095ea7b31461016c57806318160ddd1461019c57806323b872dd146101c557600080fd5b3661011f57005b600080fd5b34801561013057600080fd5b5060408051808201909152600d81526c4469676974616c5477696e414960981b60208201525b6040516101639190610daf565b60405180910390f35b34801561017857600080fd5b5061018c610187366004610e19565b6103d5565b6040519015158152602001610163565b3480156101a857600080fd5b506b033b2e3c9fd0803ce80000005b604051908152602001610163565b3480156101d157600080fd5b5061018c6101e0366004610e43565b6103ec565b3480156101f157600080fd5b5060405160128152602001610163565b34801561020d57600080fd5b506101b760025481565b34801561022357600080fd5b506101b7610232366004610e7f565b6001600160a01b031660009081526007602052604090205490565b34801561025957600080fd5b5061026261043e565b005b34801561027057600080fd5b506102626104bb565b34801561028557600080fd5b506101b760065481565b34801561029b57600080fd5b506000546040516001600160a01b039091168152602001610163565b3480156102c357600080fd5b506102626102d2366004610ea1565b6104f7565b3480156102e357600080fd5b506040805180820190915260048152634454414960e01b6020820152610156565b34801561031057600080fd5b5061018c61031f366004610e19565b61052c565b34801561033057600080fd5b50610262610539565b34801561034557600080fd5b506101b760035481565b34801561035b57600080fd5b5061026261036a366004610e7f565b610576565b34801561037b57600080fd5b506101b761038a366004610ec3565b6001600160a01b03918216600090815260086020908152604080832093909416825291909152205490565b3480156103c157600080fd5b506102626103d0366004610e7f565b6105c4565b60006103e23384846105fa565b5060015b92915050565b60006103f984848461071e565b6001600160a01b03841660009081526008602090815260408083203380855292529091205461043491869161042f908690610f0c565b6105fa565b5060019392505050565b6000546001600160a01b031633146104715760405162461bcd60e51b815260040161046890610f1f565b60405180910390fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031633146104e55760405162461bcd60e51b815260040161046890610f1f565b6b033b2e3c9fd0803ce8000000600655565b6000546001600160a01b031633146105215760405162461bcd60e51b815260040161046890610f1f565b600291909155600355565b60006103e233848461071e565b6000546001600160a01b031633146105635760405162461bcd60e51b815260040161046890610f1f565b6004805460ff1916600117905543600555565b6000546001600160a01b031633146105a05760405162461bcd60e51b815260040161046890610f1f565b6001600160a01b03166000908152600960205260409020805460ff19166001179055565b6000546001600160a01b031633146105ee5760405162461bcd60e51b815260040161046890610f1f565b6105f781610cef565b50565b6001600160a01b03831661065c5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610468565b6001600160a01b0382166106bd5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610468565b6001600160a01b0383811660008181526008602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166107825760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610468565b633b9aca0081116107c85760405162461bcd60e51b815260206004820152601060248201526f135a5b881d1c985b9cd9995c88185b5d60821b6044820152606401610468565b6001600160a01b03831660009081526009602052604081205460ff168061080757506001600160a01b03831660009081526009602052604090205460ff165b1561081457506000610b7e565b60045460ff161580159061082a57506006548211155b6108815760405162461bcd60e51b815260206004820152602260248201527f4c61756e6368202f204d6178205478416d6f756e74203225206174206c61756e6044820152610c6d60f31b6064820152608401610468565b600454610100900460ff16600103610942576001600160a01b038416600090815260076020526040812080548492906108bb908490610f0c565b90915550506001600160a01b038316600090815260076020526040812080548492906108e8908490610f54565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161093491815260200190565b60405180910390a350505050565b7f000000000000000000000000ad8ef62800cb41589cb3b2933fb526f1dc7c4fdc6001600160a01b0316846001600160a01b0316036109845750600254610b7e565b7f000000000000000000000000ad8ef62800cb41589cb3b2933fb526f1dc7c4fdc6001600160a01b0316836001600160a01b031603610b7a57306000908152600760205260409020546934f086f3b33b68400000811180156109ee5750600454610100900460ff16155b15610b70576a084595161401484a000000811115610a1457506a084595161401484a0000005b6004805461ff0019166101001790556040805160028082526060820183526000926020830190803683370190505090503081600081518110610a5857610a58610f67565b60200260200101906001600160a01b031690816001600160a01b0316815250507f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281600181518110610aac57610aac610f67565b6001600160a01b03928316602091820292909201015260405163791ac94760e01b81527f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d9091169063791ac94790610b3190859060009086907f000000000000000000000000215bdff23dd182c902533b4ad921ff16c3bd40cc904290600401610f7d565b600060405180830381600087803b158015610b4b57600080fd5b505af1158015610b5f573d6000803e3d6000fd5b50506004805461ff00191690555050505b5050600354610b7e565b5060005b8015610cc15760006064610b928385610fee565b610b9c9190611005565b90506000610baa8285610f0c565b6001600160a01b038716600090815260076020526040812080549293508692909190610bd7908490610f0c565b90915550506001600160a01b03851660009081526007602052604081208054839290610c04908490610f54565b90915550503060009081526007602052604081208054849290610c28908490610f54565b909155505060405182815230906001600160a01b038816907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3846001600160a01b0316866001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610cb291815260200190565b60405180910390a35050610ce9565b6001600160a01b038416600090815260076020526040812080548492906108bb908490610f0c565b50505050565b6001600160a01b038116610d545760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610468565b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b600060208083528351808285015260005b81811015610ddc57858101830151858201604001528201610dc0565b506000604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b0381168114610e1457600080fd5b919050565b60008060408385031215610e2c57600080fd5b610e3583610dfd565b946020939093013593505050565b600080600060608486031215610e5857600080fd5b610e6184610dfd565b9250610e6f60208501610dfd565b9150604084013590509250925092565b600060208284031215610e9157600080fd5b610e9a82610dfd565b9392505050565b60008060408385031215610eb457600080fd5b50508035926020909101359150565b60008060408385031215610ed657600080fd5b610edf83610dfd565b9150610eed60208401610dfd565b90509250929050565b634e487b7160e01b600052601160045260246000fd5b818103818111156103e6576103e6610ef6565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b808201808211156103e6576103e6610ef6565b634e487b7160e01b600052603260045260246000fd5b600060a082018783526020878185015260a0604085015281875180845260c086019150828901935060005b81811015610fcd5784516001600160a01b031683529383019391830191600101610fa8565b50506001600160a01b03969096166060850152505050608001529392505050565b80820281158282048414176103e6576103e6610ef6565b60008261102257634e487b7160e01b600052601260045260246000fd5b50049056fea2646970667358221220825532ab61c5b2734d6bd5994ccb86717030d8ade1366ff1af1ce2038dafa36364736f6c63430008120033
|
/**
DigitalTwinAI | $DTAI- Premier DeSEP protocol building the first decentralized and web3-powered engine to generate digital data for training AI models
**/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.18;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
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
);
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
}
contract DTwinAI is Context, IERC20, Ownable {
uint256 private constant _totalSupply = 1_000_000_000e18;
uint256 private constant onePercent = 10_000_000e18;
uint256 private constant minSwap = 250_000e18;
uint8 private constant _decimals = 18;
IUniswapV2Router02 immutable uniswapV2Router;
address immutable uniswapV2Pair;
address immutable WETH;
address payable immutable marketingWallet;
uint256 public buyTax;
uint256 public sellTax;
uint8 private launch;
uint8 private inSwapAndLiquify;
uint256 private launchBlock;
uint256 public maxTxAmount = onePercent; //max Tx for first mins after launch
string private constant _name = "DigitalTwinAI";
string private constant _symbol = "DTAI";
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFeeWallet;
constructor() {
uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
WETH = uniswapV2Router.WETH();
buyTax = 25;
sellTax = 40; // Initial tax set for bot minimization, will change right after launch
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(
address(this),
WETH
);
marketingWallet = payable(0x215BDFf23dd182C902533B4aD921Ff16c3bD40Cc);
_balance[msg.sender] = _totalSupply;
_isExcludedFromFeeWallet[marketingWallet] = true;
_isExcludedFromFeeWallet[msg.sender] = true;
_isExcludedFromFeeWallet[address(this)] = true;
_allowances[address(this)][address(uniswapV2Router)] = type(uint256)
.max;
_allowances[msg.sender][address(uniswapV2Router)] = type(uint256).max;
_allowances[marketingWallet][address(uniswapV2Router)] = type(uint256)
.max;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balance[account];
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()] - amount
);
return true;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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 openTrading() external onlyOwner {
launch = 1;
launchBlock = block.number;
}
function addExcludedWallet(address wallet) external onlyOwner {
_isExcludedFromFeeWallet[wallet] = true;
}
function removeLimits() external onlyOwner {
maxTxAmount = _totalSupply;
}
function changeTax(uint256 newBuyTax, uint256 newSellTax) external onlyOwner {
buyTax = newBuyTax;
sellTax = newSellTax;
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 1e9, "Min transfer amt");
uint256 _tax;
if (_isExcludedFromFeeWallet[from] || _isExcludedFromFeeWallet[to]) {
_tax = 0;
} else {
require(
launch != 0 && amount <= maxTxAmount,
"Launch / Max TxAmount 2% at launch"
);
if (inSwapAndLiquify == 1) {
//No tax transfer
_balance[from] -= amount;
_balance[to] += amount;
emit Transfer(from, to, amount);
return;
}
if (from == uniswapV2Pair) {
_tax = buyTax;
} else if (to == uniswapV2Pair) {
uint256 tokensToSwap = _balance[address(this)];
if (tokensToSwap > minSwap && inSwapAndLiquify == 0) {
if (tokensToSwap > onePercent) {
tokensToSwap = onePercent;
}
inSwapAndLiquify = 1;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WETH;
uniswapV2Router
.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokensToSwap,
0,
path,
marketingWallet,
block.timestamp
);
inSwapAndLiquify = 0;
}
_tax = sellTax;
} else {
_tax = 0;
}
}
//Is there tax for sender|receiver?
if (_tax != 0) {
//Tax transfer
uint256 taxTokens = (amount * _tax) / 100;
uint256 transferAmount = amount - taxTokens;
_balance[from] -= amount;
_balance[to] += transferAmount;
_balance[address(this)] += taxTokens;
emit Transfer(from, address(this), taxTokens);
emit Transfer(from, to, transferAmount);
} else {
//No tax transfer
_balance[from] -= amount;
_balance[to] += amount;
emit Transfer(from, to, amount);
}
}
receive() external payable {}
}
|
1 | 19,499,917 |
78833f509da6a64e85e9cfc36e237828d9bd1b26aeb10dd0e070f49386ef406b
|
0304672d41e1303459a44d4be6d7b46ba09fa0d21642124c168b7824cd9d1cc8
|
215bdff23dd182c902533b4ad921ff16c3bd40cc
|
5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f
|
ad8ef62800cb41589cb3b2933fb526f1dc7c4fdc
|
60806040526001600c5534801561001557600080fd5b506040514690806052612d228239604080519182900360520182208282018252600a8352692ab734b9bbb0b8102b1960b11b6020938401528151808301835260018152603160f81b908401528151808401919091527fbfcc8ef98ffbf7b6c3fec7bf5185b566b9863e35a9d83acd49ad6824b5969738818301527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6606082015260808101949094523060a0808601919091528151808603909101815260c09094019052825192019190912060035550600580546001600160a01b03191633179055612c1d806101056000396000f3fe608060405234801561001057600080fd5b50600436106101b95760003560e01c80636a627842116100f9578063ba9a7a5611610097578063d21220a711610071578063d21220a7146105da578063d505accf146105e2578063dd62ed3e14610640578063fff6cae91461067b576101b9565b8063ba9a7a5614610597578063bc25cf771461059f578063c45a0155146105d2576101b9565b80637ecebe00116100d35780637ecebe00146104d757806389afcb441461050a57806395d89b4114610556578063a9059cbb1461055e576101b9565b80636a6278421461046957806370a082311461049c5780637464fc3d146104cf576101b9565b806323b872dd116101665780633644e515116101405780633644e51514610416578063485cc9551461041e5780635909c0d5146104595780635a3d549314610461576101b9565b806323b872dd146103ad57806330adf81f146103f0578063313ce567146103f8576101b9565b8063095ea7b311610197578063095ea7b3146103155780630dfe16811461036257806318160ddd14610393576101b9565b8063022c0d9f146101be57806306fdde03146102595780630902f1ac146102d6575b600080fd5b610257600480360360808110156101d457600080fd5b81359160208101359173ffffffffffffffffffffffffffffffffffffffff604083013516919081019060808101606082013564010000000081111561021857600080fd5b82018360208201111561022a57600080fd5b8035906020019184600183028401116401000000008311171561024c57600080fd5b509092509050610683565b005b610261610d57565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561029b578181015183820152602001610283565b50505050905090810190601f1680156102c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102de610d90565b604080516dffffffffffffffffffffffffffff948516815292909316602083015263ffffffff168183015290519081900360600190f35b61034e6004803603604081101561032b57600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135169060200135610de5565b604080519115158252519081900360200190f35b61036a610dfc565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b61039b610e18565b60408051918252519081900360200190f35b61034e600480360360608110156103c357600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060400135610e1e565b61039b610efd565b610400610f21565b6040805160ff9092168252519081900360200190f35b61039b610f26565b6102576004803603604081101561043457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516610f2c565b61039b611005565b61039b61100b565b61039b6004803603602081101561047f57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16611011565b61039b600480360360208110156104b257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113cb565b61039b6113dd565b61039b600480360360208110156104ed57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113e3565b61053d6004803603602081101561052057600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113f5565b6040805192835260208301919091528051918290030190f35b610261611892565b61034e6004803603604081101561057457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001356118cb565b61039b6118d8565b610257600480360360208110156105b557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166118de565b61036a611ad4565b61036a611af0565b610257600480360360e08110156105f857600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060408101359060608101359060ff6080820135169060a08101359060c00135611b0c565b61039b6004803603604081101561065657600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516611dd8565b610257611df5565b600c546001146106f457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55841515806107075750600084115b61075c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180612b2f6025913960400191505060405180910390fd5b600080610767610d90565b5091509150816dffffffffffffffffffffffffffff168710801561079a5750806dffffffffffffffffffffffffffff1686105b6107ef576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612b786021913960400191505060405180910390fd5b600654600754600091829173ffffffffffffffffffffffffffffffffffffffff91821691908116908916821480159061085457508073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff1614155b6108bf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f556e697377617056323a20494e56414c49445f544f0000000000000000000000604482015290519081900360640190fd5b8a156108d0576108d0828a8d611fdb565b89156108e1576108e1818a8c611fdb565b86156109c3578873ffffffffffffffffffffffffffffffffffffffff166310d1e85c338d8d8c8c6040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509650505050505050600060405180830381600087803b1580156109aa57600080fd5b505af11580156109be573d6000803e3d6000fd5b505050505b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8416916370a08231916024808301926020929190829003018186803b158015610a2f57600080fd5b505afa158015610a43573d6000803e3d6000fd5b505050506040513d6020811015610a5957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191955073ffffffffffffffffffffffffffffffffffffffff8316916370a0823191602480820192602092909190829003018186803b158015610acb57600080fd5b505afa158015610adf573d6000803e3d6000fd5b505050506040513d6020811015610af557600080fd5b5051925060009150506dffffffffffffffffffffffffffff85168a90038311610b1f576000610b35565b89856dffffffffffffffffffffffffffff160383035b9050600089856dffffffffffffffffffffffffffff16038311610b59576000610b6f565b89856dffffffffffffffffffffffffffff160383035b90506000821180610b805750600081115b610bd5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612b546024913960400191505060405180910390fd5b6000610c09610beb84600363ffffffff6121e816565b610bfd876103e863ffffffff6121e816565b9063ffffffff61226e16565b90506000610c21610beb84600363ffffffff6121e816565b9050610c59620f4240610c4d6dffffffffffffffffffffffffffff8b8116908b1663ffffffff6121e816565b9063ffffffff6121e816565b610c69838363ffffffff6121e816565b1015610cd657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f556e697377617056323a204b0000000000000000000000000000000000000000604482015290519081900360640190fd5b5050610ce4848488886122e0565b60408051838152602081018390528082018d9052606081018c9052905173ffffffffffffffffffffffffffffffffffffffff8b169133917fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8229181900360800190a350506001600c55505050505050505050565b6040518060400160405280600a81526020017f556e69737761702056320000000000000000000000000000000000000000000081525081565b6008546dffffffffffffffffffffffffffff808216926e0100000000000000000000000000008304909116917c0100000000000000000000000000000000000000000000000000000000900463ffffffff1690565b6000610df233848461259c565b5060015b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff1681565b60005481565b73ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083203384529091528120547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14610ee85773ffffffffffffffffffffffffffffffffffffffff84166000908152600260209081526040808320338452909152902054610eb6908363ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff851660009081526002602090815260408083203384529091529020555b610ef384848461260b565b5060019392505050565b7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b601281565b60035481565b60055473ffffffffffffffffffffffffffffffffffffffff163314610fb257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f556e697377617056323a20464f5242494444454e000000000000000000000000604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560078054929093169116179055565b60095481565b600a5481565b6000600c5460011461108457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611094610d90565b50600654604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905193955091935060009273ffffffffffffffffffffffffffffffffffffffff909116916370a08231916024808301926020929190829003018186803b15801561110e57600080fd5b505afa158015611122573d6000803e3d6000fd5b505050506040513d602081101561113857600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905192935060009273ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b1580156111b157600080fd5b505afa1580156111c5573d6000803e3d6000fd5b505050506040513d60208110156111db57600080fd5b505190506000611201836dffffffffffffffffffffffffffff871663ffffffff61226e16565b90506000611225836dffffffffffffffffffffffffffff871663ffffffff61226e16565b9050600061123387876126ec565b600054909150806112705761125c6103e8610bfd611257878763ffffffff6121e816565b612878565b985061126b60006103e86128ca565b6112cd565b6112ca6dffffffffffffffffffffffffffff8916611294868463ffffffff6121e816565b8161129b57fe5b046dffffffffffffffffffffffffffff89166112bd868563ffffffff6121e816565b816112c457fe5b0461297a565b98505b60008911611326576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612bc16028913960400191505060405180910390fd5b6113308a8a6128ca565b61133c86868a8a6122e0565b811561137e5760085461137a906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b6040805185815260208101859052815133927f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f928290030190a250506001600c5550949695505050505050565b60016020526000908152604090205481565b600b5481565b60046020526000908152604090205481565b600080600c5460011461146957604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611479610d90565b50600654600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905194965092945073ffffffffffffffffffffffffffffffffffffffff9182169391169160009184916370a08231916024808301926020929190829003018186803b1580156114fb57600080fd5b505afa15801561150f573d6000803e3d6000fd5b505050506040513d602081101561152557600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191925060009173ffffffffffffffffffffffffffffffffffffffff8516916370a08231916024808301926020929190829003018186803b15801561159957600080fd5b505afa1580156115ad573d6000803e3d6000fd5b505050506040513d60208110156115c357600080fd5b5051306000908152600160205260408120549192506115e288886126ec565b600054909150806115f9848763ffffffff6121e816565b8161160057fe5b049a5080611614848663ffffffff6121e816565b8161161b57fe5b04995060008b11801561162e575060008a115b611683576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612b996028913960400191505060405180910390fd5b61168d3084612992565b611698878d8d611fdb565b6116a3868d8c611fdb565b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8916916370a08231916024808301926020929190829003018186803b15801561170f57600080fd5b505afa158015611723573d6000803e3d6000fd5b505050506040513d602081101561173957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191965073ffffffffffffffffffffffffffffffffffffffff8816916370a0823191602480820192602092909190829003018186803b1580156117ab57600080fd5b505afa1580156117bf573d6000803e3d6000fd5b505050506040513d60208110156117d557600080fd5b505193506117e585858b8b6122e0565b811561182757600854611823906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b604080518c8152602081018c9052815173ffffffffffffffffffffffffffffffffffffffff8f169233927fdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496929081900390910190a35050505050505050506001600c81905550915091565b6040518060400160405280600681526020017f554e492d5632000000000000000000000000000000000000000000000000000081525081565b6000610df233848461260b565b6103e881565b600c5460011461194f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654600754600854604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff9485169490931692611a2b9285928792611a26926dffffffffffffffffffffffffffff169185916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b505afa158015611a02573d6000803e3d6000fd5b505050506040513d6020811015611a1857600080fd5b50519063ffffffff61226e16565b611fdb565b600854604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611aca9284928792611a26926e01000000000000000000000000000090046dffffffffffffffffffffffffffff169173ffffffffffffffffffffffffffffffffffffffff8616916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b50506001600c5550565b60055473ffffffffffffffffffffffffffffffffffffffff1681565b60075473ffffffffffffffffffffffffffffffffffffffff1681565b42841015611b7b57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f556e697377617056323a20455850495245440000000000000000000000000000604482015290519081900360640190fd5b60035473ffffffffffffffffffffffffffffffffffffffff80891660008181526004602090815260408083208054600180820190925582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98186015280840196909652958d166060860152608085018c905260a085019590955260c08085018b90528151808603909101815260e0850182528051908301207f19010000000000000000000000000000000000000000000000000000000000006101008601526101028501969096526101228085019690965280518085039096018652610142840180825286519683019690962095839052610162840180825286905260ff89166101828501526101a284018890526101c28401879052519193926101e2808201937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081019281900390910190855afa158015611cdc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811615801590611d5757508873ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16145b611dc257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f556e697377617056323a20494e56414c49445f5349474e415455524500000000604482015290519081900360640190fd5b611dcd89898961259c565b505050505050505050565b600260209081526000928352604080842090915290825290205481565b600c54600114611e6657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611fd49273ffffffffffffffffffffffffffffffffffffffff16916370a08231916024808301926020929190829003018186803b158015611edd57600080fd5b505afa158015611ef1573d6000803e3d6000fd5b505050506040513d6020811015611f0757600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b158015611f7a57600080fd5b505afa158015611f8e573d6000803e3d6000fd5b505050506040513d6020811015611fa457600080fd5b50516008546dffffffffffffffffffffffffffff808216916e0100000000000000000000000000009004166122e0565b6001600c55565b604080518082018252601981527f7472616e7366657228616464726573732c75696e743235362900000000000000602091820152815173ffffffffffffffffffffffffffffffffffffffff85811660248301526044808301869052845180840390910181526064909201845291810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001781529251815160009460609489169392918291908083835b602083106120e157805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe090920191602091820191016120a4565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612143576040519150601f19603f3d011682016040523d82523d6000602084013e612148565b606091505b5091509150818015612176575080511580612176575080806020019051602081101561217357600080fd5b50515b6121e157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f556e697377617056323a205452414e534645525f4641494c4544000000000000604482015290519081900360640190fd5b5050505050565b60008115806122035750508082028282828161220057fe5b04145b610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6d756c2d6f766572666c6f77000000000000000000000000604482015290519081900360640190fd5b80820382811115610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f64732d6d6174682d7375622d756e646572666c6f770000000000000000000000604482015290519081900360640190fd5b6dffffffffffffffffffffffffffff841180159061230c57506dffffffffffffffffffffffffffff8311155b61237757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f556e697377617056323a204f564552464c4f5700000000000000000000000000604482015290519081900360640190fd5b60085463ffffffff428116917c0100000000000000000000000000000000000000000000000000000000900481168203908116158015906123c757506dffffffffffffffffffffffffffff841615155b80156123e257506dffffffffffffffffffffffffffff831615155b15612492578063ffffffff16612425856123fb86612a57565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff169063ffffffff612a7b16565b600980547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff929092169290920201905563ffffffff8116612465846123fb87612a57565b600a80547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff92909216929092020190555b600880547fffffffffffffffffffffffffffffffffffff0000000000000000000000000000166dffffffffffffffffffffffffffff888116919091177fffffffff0000000000000000000000000000ffffffffffffffffffffffffffff166e0100000000000000000000000000008883168102919091177bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167c010000000000000000000000000000000000000000000000000000000063ffffffff871602179283905560408051848416815291909304909116602082015281517f1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1929181900390910190a1505050505050565b73ffffffffffffffffffffffffffffffffffffffff808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b73ffffffffffffffffffffffffffffffffffffffff8316600090815260016020526040902054612641908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff8085166000908152600160205260408082209390935590841681522054612683908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff80841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663017e7e586040518163ffffffff1660e01b815260040160206040518083038186803b15801561275757600080fd5b505afa15801561276b573d6000803e3d6000fd5b505050506040513d602081101561278157600080fd5b5051600b5473ffffffffffffffffffffffffffffffffffffffff821615801594509192509061286457801561285f5760006127d86112576dffffffffffffffffffffffffffff88811690881663ffffffff6121e816565b905060006127e583612878565b90508082111561285c576000612813612804848463ffffffff61226e16565b6000549063ffffffff6121e816565b905060006128388361282c86600563ffffffff6121e816565b9063ffffffff612abc16565b9050600081838161284557fe5b04905080156128585761285887826128ca565b5050505b50505b612870565b8015612870576000600b555b505092915050565b600060038211156128bb575080600160028204015b818110156128b5578091506002818285816128a457fe5b0401816128ad57fe5b04905061288d565b506128c5565b81156128c5575060015b919050565b6000546128dd908263ffffffff612abc16565b600090815573ffffffffffffffffffffffffffffffffffffffff8316815260016020526040902054612915908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000818310612989578161298b565b825b9392505050565b73ffffffffffffffffffffffffffffffffffffffff82166000908152600160205260409020546129c8908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff831660009081526001602052604081209190915554612a02908263ffffffff61226e16565b600090815560408051838152905173ffffffffffffffffffffffffffffffffffffffff8516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef919081900360200190a35050565b6dffffffffffffffffffffffffffff166e0100000000000000000000000000000290565b60006dffffffffffffffffffffffffffff82167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff841681612ab457fe5b049392505050565b80820182811015610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6164642d6f766572666c6f77000000000000000000000000604482015290519081900360640190fdfe556e697377617056323a20494e53554646494349454e545f4f55545055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f494e5055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f4c4951554944495459556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4255524e4544556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4d494e544544a265627a7a723158207dca18479e58487606bf70c79e44d8dee62353c9ee6d01f9a9d70885b8765f2264736f6c63430005100032454950373132446f6d61696e28737472696e67206e616d652c737472696e672076657273696f6e2c75696e7432353620636861696e49642c6164647265737320766572696679696e67436f6e747261637429
|
608060405234801561001057600080fd5b50600436106101b95760003560e01c80636a627842116100f9578063ba9a7a5611610097578063d21220a711610071578063d21220a7146105da578063d505accf146105e2578063dd62ed3e14610640578063fff6cae91461067b576101b9565b8063ba9a7a5614610597578063bc25cf771461059f578063c45a0155146105d2576101b9565b80637ecebe00116100d35780637ecebe00146104d757806389afcb441461050a57806395d89b4114610556578063a9059cbb1461055e576101b9565b80636a6278421461046957806370a082311461049c5780637464fc3d146104cf576101b9565b806323b872dd116101665780633644e515116101405780633644e51514610416578063485cc9551461041e5780635909c0d5146104595780635a3d549314610461576101b9565b806323b872dd146103ad57806330adf81f146103f0578063313ce567146103f8576101b9565b8063095ea7b311610197578063095ea7b3146103155780630dfe16811461036257806318160ddd14610393576101b9565b8063022c0d9f146101be57806306fdde03146102595780630902f1ac146102d6575b600080fd5b610257600480360360808110156101d457600080fd5b81359160208101359173ffffffffffffffffffffffffffffffffffffffff604083013516919081019060808101606082013564010000000081111561021857600080fd5b82018360208201111561022a57600080fd5b8035906020019184600183028401116401000000008311171561024c57600080fd5b509092509050610683565b005b610261610d57565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561029b578181015183820152602001610283565b50505050905090810190601f1680156102c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102de610d90565b604080516dffffffffffffffffffffffffffff948516815292909316602083015263ffffffff168183015290519081900360600190f35b61034e6004803603604081101561032b57600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135169060200135610de5565b604080519115158252519081900360200190f35b61036a610dfc565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b61039b610e18565b60408051918252519081900360200190f35b61034e600480360360608110156103c357600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060400135610e1e565b61039b610efd565b610400610f21565b6040805160ff9092168252519081900360200190f35b61039b610f26565b6102576004803603604081101561043457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516610f2c565b61039b611005565b61039b61100b565b61039b6004803603602081101561047f57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16611011565b61039b600480360360208110156104b257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113cb565b61039b6113dd565b61039b600480360360208110156104ed57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113e3565b61053d6004803603602081101561052057600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113f5565b6040805192835260208301919091528051918290030190f35b610261611892565b61034e6004803603604081101561057457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001356118cb565b61039b6118d8565b610257600480360360208110156105b557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166118de565b61036a611ad4565b61036a611af0565b610257600480360360e08110156105f857600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060408101359060608101359060ff6080820135169060a08101359060c00135611b0c565b61039b6004803603604081101561065657600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516611dd8565b610257611df5565b600c546001146106f457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55841515806107075750600084115b61075c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180612b2f6025913960400191505060405180910390fd5b600080610767610d90565b5091509150816dffffffffffffffffffffffffffff168710801561079a5750806dffffffffffffffffffffffffffff1686105b6107ef576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612b786021913960400191505060405180910390fd5b600654600754600091829173ffffffffffffffffffffffffffffffffffffffff91821691908116908916821480159061085457508073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff1614155b6108bf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f556e697377617056323a20494e56414c49445f544f0000000000000000000000604482015290519081900360640190fd5b8a156108d0576108d0828a8d611fdb565b89156108e1576108e1818a8c611fdb565b86156109c3578873ffffffffffffffffffffffffffffffffffffffff166310d1e85c338d8d8c8c6040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509650505050505050600060405180830381600087803b1580156109aa57600080fd5b505af11580156109be573d6000803e3d6000fd5b505050505b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8416916370a08231916024808301926020929190829003018186803b158015610a2f57600080fd5b505afa158015610a43573d6000803e3d6000fd5b505050506040513d6020811015610a5957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191955073ffffffffffffffffffffffffffffffffffffffff8316916370a0823191602480820192602092909190829003018186803b158015610acb57600080fd5b505afa158015610adf573d6000803e3d6000fd5b505050506040513d6020811015610af557600080fd5b5051925060009150506dffffffffffffffffffffffffffff85168a90038311610b1f576000610b35565b89856dffffffffffffffffffffffffffff160383035b9050600089856dffffffffffffffffffffffffffff16038311610b59576000610b6f565b89856dffffffffffffffffffffffffffff160383035b90506000821180610b805750600081115b610bd5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612b546024913960400191505060405180910390fd5b6000610c09610beb84600363ffffffff6121e816565b610bfd876103e863ffffffff6121e816565b9063ffffffff61226e16565b90506000610c21610beb84600363ffffffff6121e816565b9050610c59620f4240610c4d6dffffffffffffffffffffffffffff8b8116908b1663ffffffff6121e816565b9063ffffffff6121e816565b610c69838363ffffffff6121e816565b1015610cd657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f556e697377617056323a204b0000000000000000000000000000000000000000604482015290519081900360640190fd5b5050610ce4848488886122e0565b60408051838152602081018390528082018d9052606081018c9052905173ffffffffffffffffffffffffffffffffffffffff8b169133917fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8229181900360800190a350506001600c55505050505050505050565b6040518060400160405280600a81526020017f556e69737761702056320000000000000000000000000000000000000000000081525081565b6008546dffffffffffffffffffffffffffff808216926e0100000000000000000000000000008304909116917c0100000000000000000000000000000000000000000000000000000000900463ffffffff1690565b6000610df233848461259c565b5060015b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff1681565b60005481565b73ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083203384529091528120547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14610ee85773ffffffffffffffffffffffffffffffffffffffff84166000908152600260209081526040808320338452909152902054610eb6908363ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff851660009081526002602090815260408083203384529091529020555b610ef384848461260b565b5060019392505050565b7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b601281565b60035481565b60055473ffffffffffffffffffffffffffffffffffffffff163314610fb257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f556e697377617056323a20464f5242494444454e000000000000000000000000604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560078054929093169116179055565b60095481565b600a5481565b6000600c5460011461108457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611094610d90565b50600654604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905193955091935060009273ffffffffffffffffffffffffffffffffffffffff909116916370a08231916024808301926020929190829003018186803b15801561110e57600080fd5b505afa158015611122573d6000803e3d6000fd5b505050506040513d602081101561113857600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905192935060009273ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b1580156111b157600080fd5b505afa1580156111c5573d6000803e3d6000fd5b505050506040513d60208110156111db57600080fd5b505190506000611201836dffffffffffffffffffffffffffff871663ffffffff61226e16565b90506000611225836dffffffffffffffffffffffffffff871663ffffffff61226e16565b9050600061123387876126ec565b600054909150806112705761125c6103e8610bfd611257878763ffffffff6121e816565b612878565b985061126b60006103e86128ca565b6112cd565b6112ca6dffffffffffffffffffffffffffff8916611294868463ffffffff6121e816565b8161129b57fe5b046dffffffffffffffffffffffffffff89166112bd868563ffffffff6121e816565b816112c457fe5b0461297a565b98505b60008911611326576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612bc16028913960400191505060405180910390fd5b6113308a8a6128ca565b61133c86868a8a6122e0565b811561137e5760085461137a906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b6040805185815260208101859052815133927f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f928290030190a250506001600c5550949695505050505050565b60016020526000908152604090205481565b600b5481565b60046020526000908152604090205481565b600080600c5460011461146957604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611479610d90565b50600654600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905194965092945073ffffffffffffffffffffffffffffffffffffffff9182169391169160009184916370a08231916024808301926020929190829003018186803b1580156114fb57600080fd5b505afa15801561150f573d6000803e3d6000fd5b505050506040513d602081101561152557600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191925060009173ffffffffffffffffffffffffffffffffffffffff8516916370a08231916024808301926020929190829003018186803b15801561159957600080fd5b505afa1580156115ad573d6000803e3d6000fd5b505050506040513d60208110156115c357600080fd5b5051306000908152600160205260408120549192506115e288886126ec565b600054909150806115f9848763ffffffff6121e816565b8161160057fe5b049a5080611614848663ffffffff6121e816565b8161161b57fe5b04995060008b11801561162e575060008a115b611683576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612b996028913960400191505060405180910390fd5b61168d3084612992565b611698878d8d611fdb565b6116a3868d8c611fdb565b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8916916370a08231916024808301926020929190829003018186803b15801561170f57600080fd5b505afa158015611723573d6000803e3d6000fd5b505050506040513d602081101561173957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191965073ffffffffffffffffffffffffffffffffffffffff8816916370a0823191602480820192602092909190829003018186803b1580156117ab57600080fd5b505afa1580156117bf573d6000803e3d6000fd5b505050506040513d60208110156117d557600080fd5b505193506117e585858b8b6122e0565b811561182757600854611823906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b604080518c8152602081018c9052815173ffffffffffffffffffffffffffffffffffffffff8f169233927fdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496929081900390910190a35050505050505050506001600c81905550915091565b6040518060400160405280600681526020017f554e492d5632000000000000000000000000000000000000000000000000000081525081565b6000610df233848461260b565b6103e881565b600c5460011461194f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654600754600854604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff9485169490931692611a2b9285928792611a26926dffffffffffffffffffffffffffff169185916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b505afa158015611a02573d6000803e3d6000fd5b505050506040513d6020811015611a1857600080fd5b50519063ffffffff61226e16565b611fdb565b600854604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611aca9284928792611a26926e01000000000000000000000000000090046dffffffffffffffffffffffffffff169173ffffffffffffffffffffffffffffffffffffffff8616916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b50506001600c5550565b60055473ffffffffffffffffffffffffffffffffffffffff1681565b60075473ffffffffffffffffffffffffffffffffffffffff1681565b42841015611b7b57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f556e697377617056323a20455850495245440000000000000000000000000000604482015290519081900360640190fd5b60035473ffffffffffffffffffffffffffffffffffffffff80891660008181526004602090815260408083208054600180820190925582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98186015280840196909652958d166060860152608085018c905260a085019590955260c08085018b90528151808603909101815260e0850182528051908301207f19010000000000000000000000000000000000000000000000000000000000006101008601526101028501969096526101228085019690965280518085039096018652610142840180825286519683019690962095839052610162840180825286905260ff89166101828501526101a284018890526101c28401879052519193926101e2808201937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081019281900390910190855afa158015611cdc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811615801590611d5757508873ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16145b611dc257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f556e697377617056323a20494e56414c49445f5349474e415455524500000000604482015290519081900360640190fd5b611dcd89898961259c565b505050505050505050565b600260209081526000928352604080842090915290825290205481565b600c54600114611e6657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611fd49273ffffffffffffffffffffffffffffffffffffffff16916370a08231916024808301926020929190829003018186803b158015611edd57600080fd5b505afa158015611ef1573d6000803e3d6000fd5b505050506040513d6020811015611f0757600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b158015611f7a57600080fd5b505afa158015611f8e573d6000803e3d6000fd5b505050506040513d6020811015611fa457600080fd5b50516008546dffffffffffffffffffffffffffff808216916e0100000000000000000000000000009004166122e0565b6001600c55565b604080518082018252601981527f7472616e7366657228616464726573732c75696e743235362900000000000000602091820152815173ffffffffffffffffffffffffffffffffffffffff85811660248301526044808301869052845180840390910181526064909201845291810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001781529251815160009460609489169392918291908083835b602083106120e157805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe090920191602091820191016120a4565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612143576040519150601f19603f3d011682016040523d82523d6000602084013e612148565b606091505b5091509150818015612176575080511580612176575080806020019051602081101561217357600080fd5b50515b6121e157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f556e697377617056323a205452414e534645525f4641494c4544000000000000604482015290519081900360640190fd5b5050505050565b60008115806122035750508082028282828161220057fe5b04145b610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6d756c2d6f766572666c6f77000000000000000000000000604482015290519081900360640190fd5b80820382811115610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f64732d6d6174682d7375622d756e646572666c6f770000000000000000000000604482015290519081900360640190fd5b6dffffffffffffffffffffffffffff841180159061230c57506dffffffffffffffffffffffffffff8311155b61237757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f556e697377617056323a204f564552464c4f5700000000000000000000000000604482015290519081900360640190fd5b60085463ffffffff428116917c0100000000000000000000000000000000000000000000000000000000900481168203908116158015906123c757506dffffffffffffffffffffffffffff841615155b80156123e257506dffffffffffffffffffffffffffff831615155b15612492578063ffffffff16612425856123fb86612a57565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff169063ffffffff612a7b16565b600980547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff929092169290920201905563ffffffff8116612465846123fb87612a57565b600a80547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff92909216929092020190555b600880547fffffffffffffffffffffffffffffffffffff0000000000000000000000000000166dffffffffffffffffffffffffffff888116919091177fffffffff0000000000000000000000000000ffffffffffffffffffffffffffff166e0100000000000000000000000000008883168102919091177bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167c010000000000000000000000000000000000000000000000000000000063ffffffff871602179283905560408051848416815291909304909116602082015281517f1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1929181900390910190a1505050505050565b73ffffffffffffffffffffffffffffffffffffffff808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b73ffffffffffffffffffffffffffffffffffffffff8316600090815260016020526040902054612641908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff8085166000908152600160205260408082209390935590841681522054612683908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff80841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663017e7e586040518163ffffffff1660e01b815260040160206040518083038186803b15801561275757600080fd5b505afa15801561276b573d6000803e3d6000fd5b505050506040513d602081101561278157600080fd5b5051600b5473ffffffffffffffffffffffffffffffffffffffff821615801594509192509061286457801561285f5760006127d86112576dffffffffffffffffffffffffffff88811690881663ffffffff6121e816565b905060006127e583612878565b90508082111561285c576000612813612804848463ffffffff61226e16565b6000549063ffffffff6121e816565b905060006128388361282c86600563ffffffff6121e816565b9063ffffffff612abc16565b9050600081838161284557fe5b04905080156128585761285887826128ca565b5050505b50505b612870565b8015612870576000600b555b505092915050565b600060038211156128bb575080600160028204015b818110156128b5578091506002818285816128a457fe5b0401816128ad57fe5b04905061288d565b506128c5565b81156128c5575060015b919050565b6000546128dd908263ffffffff612abc16565b600090815573ffffffffffffffffffffffffffffffffffffffff8316815260016020526040902054612915908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000818310612989578161298b565b825b9392505050565b73ffffffffffffffffffffffffffffffffffffffff82166000908152600160205260409020546129c8908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff831660009081526001602052604081209190915554612a02908263ffffffff61226e16565b600090815560408051838152905173ffffffffffffffffffffffffffffffffffffffff8516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef919081900360200190a35050565b6dffffffffffffffffffffffffffff166e0100000000000000000000000000000290565b60006dffffffffffffffffffffffffffff82167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff841681612ab457fe5b049392505050565b80820182811015610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6164642d6f766572666c6f77000000000000000000000000604482015290519081900360640190fdfe556e697377617056323a20494e53554646494349454e545f4f55545055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f494e5055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f4c4951554944495459556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4255524e4544556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4d494e544544a265627a7a723158207dca18479e58487606bf70c79e44d8dee62353c9ee6d01f9a9d70885b8765f2264736f6c63430005100032
|
// File: contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IUniswapV2ERC20.sol
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/UniswapV2ERC20.sol
pragma solidity =0.5.16;
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/libraries/Math.sol
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IUniswapV2Callee.sol
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: contracts/UniswapV2Pair.sol
pragma solidity =0.5.16;
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
|
1 | 19,499,917 |
78833f509da6a64e85e9cfc36e237828d9bd1b26aeb10dd0e070f49386ef406b
|
c7900b2d3b1b298d0fbda9c87c9cfc4b11a1f0a61bd44c8b1694a42d45dc3f34
|
9fc77199030f3964eae15ce1374dd29c9c3bdcba
|
9fc77199030f3964eae15ce1374dd29c9c3bdcba
|
4db2ddf3213e91f70454ca005ba2c1a23e662704
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f623d7c7f0e930d8963184340038f9af9ceb8d8c0086007557f6e75382374384e10a7b62f6258695b72d88efc120a7f2e072a8611889b2c2b0c6008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103648061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030b565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b600060208284031215610304578081fd5b5035919050565b60008282101561032957634e487b7160e01b81526011600452602481fd5b50039056fea26469706673582212201d2032e6b9599b398f41522ad8a18497eead0c1fdc8e1bb7a9cd73bf789b6e5d64736f6c63430008040033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030b565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b600060208284031215610304578081fd5b5035919050565b60008282101561032957634e487b7160e01b81526011600452602481fd5b50039056fea26469706673582212201d2032e6b9599b398f41522ad8a18497eead0c1fdc8e1bb7a9cd73bf789b6e5d64736f6c63430008040033
| |
1 | 19,499,917 |
78833f509da6a64e85e9cfc36e237828d9bd1b26aeb10dd0e070f49386ef406b
|
dfa38e22471c606827a33256b6763b63c5208b01816d4df68614e1484f61c2da
|
7aedfa2f4c5d1901faca5c6fc3bda89b3062f7dc
|
7aedfa2f4c5d1901faca5c6fc3bda89b3062f7dc
|
066ce01f9903cd4b0ee77caa607de27c2bcf4383
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f62b1cbc838b27cab7b4b813902e9a526a40fffb0d36007557f6e75382374384e10a7b62f62d4deec44f9ffde0a59bd57064cb9cee22c0b5bd76008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212204a383569535b692d71f075e2e2b9cf85f3d89f6df2dca074b362a70249b1397464736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212204a383569535b692d71f075e2e2b9cf85f3d89f6df2dca074b362a70249b1397464736f6c63430008070033
| |
1 | 19,499,918 |
26d2536a957c41ee0c49066ad23c49a5f61abd2955cb3e2a530bb7a313c549e3
|
440c658e22399c0c49f4ca8f11a0474d6ef5c967d1194b3cd46038c622bb1c5a
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
6b3aa1e61bd06645ee50b8bf72ee6fc87f7e1c53
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
776f1610be5e77da9f3351a9785939ce734bc8fda8cf961a2163f2408bc2d61c
|
4e44a3c896ed89518a4f1b8a5d300d14ad19c951
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
835d14a0e625020f5c55c1c3c82e27eb440701ed
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
37a1054f5c289f710a5ac1f25914c631c7cd3582d336e84876ae926b7692208e
|
f107c3bbbe843eae80d9e493e5286bfed47828c5
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
713e10b6a41e0daac8643097122c164a49deacd6
|
3d602d80600a3d3981f3363d3d373d3d3d363d736417c07c0e7479d10a1d35eec6344df0bc5f48f95af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d736417c07c0e7479d10a1d35eec6344df0bc5f48f95af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
6b5bfee77ccca60d892b27c8ed4d22f86d8a870a7d88d9aae1526a8b8bf14ff0
|
ce8b204429c069d8b7b8eabf682de259c281d8fa
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
86588db68983f780668e85689893f6b45993c8f2
|
3d602d80600a3d3981f3363d3d373d3d3d363d739f6be3b80088c747477b82ed5edadcc2ccc7caa75af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d739f6be3b80088c747477b82ed5edadcc2ccc7caa75af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
d8a0266837b9399a6ae4d6a1ed1472b5659a1ce2fbef127689722215ecc28e78
|
e37c4fc36df069f60fdd2f3e0704aa14741a20f4
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
353017abcb72bb8e200d7ac28ab1ba8d85a6ef1e
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
7f9f796b8ecfd80579fe3d67b3462a04df4a0c3db288bfd4553ed259101f5237
|
acf558d9b717e96c3c35443bede8bb6e46ae3159
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
46cdf8146c9e57f9eef9797885ee4c5c08c180f3
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
781876f2a7b3e04785be717d848f3d4fe471c771790574ff3824baf22addf099
|
599051266b09c8c8299d2b7c58b008db37448509
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
ec2415ac899c6d9e8b81a8c2149121b1dc425474
|
3d602d80600a3d3981f3363d3d373d3d3d363d736558d8a5ec4b9f0028ead6d1cee76a739a31ea8e5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d736558d8a5ec4b9f0028ead6d1cee76a739a31ea8e5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
262a43015869590b1eed6230907f987bb232a0966c57c5719140e5958227863e
|
859a7f6345d5891f444b64b049ed7f97bc1e5c92
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
ec35af769b6565dbd43c3a730f583f065b923930
|
3d602d80600a3d3981f3363d3d373d3d3d363d73726976dbcb0a9b9b316e0378081c8d7e54914e9b5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73726976dbcb0a9b9b316e0378081c8d7e54914e9b5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
f054a9b32fc34c237a1a190489113d9ffc34acea4b198b88eea8f2550699d042
|
f8eda15fb88c3e9844c0b8a1b5676cad559e0dab
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
0a382857cc83e054bd282496f3b3e1e8931c4085
|
3d602d80600a3d3981f3363d3d373d3d3d363d73d0d3fb081cb0d7e7a3c2da9321b41464cb3b435e5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73d0d3fb081cb0d7e7a3c2da9321b41464cb3b435e5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
e3064c340b981b88038011fa85568245886b88e08d991a8e2da364725109f1e8
|
c47f6ba27c7383a33a53a2bee2498407d3d54c59
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
f48b46a798008fa271e7e538db3b276076f037fc
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
dd3b8b01253ccce3c03270e8e1689a058f7e60317f75514722799eac02e3fc45
|
e37a151e4ba8f8b5f6f95a2f9703546e2d3ee075
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
dadbb97df22664e18883438cbca8e7eee16cddbd
|
3d602d80600a3d3981f3363d3d373d3d3d363d73f310dd6fe1955e6e8c8af0cd59542d3f45d098035af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73f310dd6fe1955e6e8c8af0cd59542d3f45d098035af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
a4efc27c429b5f0ff41de281706e33a74599b70492835ebce42c2057ce0974ab
|
6308b5154249f5c7d8dee38ffd0d1ddd0f76e404
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
07012db1916216f76a6741a4f0ed09807aa57f14
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
48e6981689876e9111f1ddb4adcb558ef5aab58b32ced7eb75fd26e20864b58b
|
8f0c8110edfaf5bd50ed45d99e081769bcf6ac37
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
4d552f7ba61d9cdbcb10292eebb75ab3ee00ac54
|
3d602d80600a3d3981f3363d3d373d3d3d363d739f6be3b80088c747477b82ed5edadcc2ccc7caa75af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d739f6be3b80088c747477b82ed5edadcc2ccc7caa75af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
505dd3f18e52022d268790fcc678da58ecb58553d420d94997e203e49e6f3135
|
ba9ccd4fc4881a349660edf552be4487235425dc
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
17116cb17b6047c6e94b57ee91115f0fb28a91f7
|
3d602d80600a3d3981f3363d3d373d3d3d363d73d3821d29dc8075f820014cf07cbcc80b02b8299a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73d3821d29dc8075f820014cf07cbcc80b02b8299a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
98eb560f528083b879ee37b7b020bfc04112afe52d49cc1459a8f6a1d0ca74be
|
3b293b4be2244de2615c62e091c4cd39c7c6dcdf
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
1b8fddb7f5bdbe571a7a678ec454d2ec2dc92017
|
3d602d80600a3d3981f3363d3d373d3d3d363d731abaec5dd9a84171d998332570919c9f0f17f2685af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d731abaec5dd9a84171d998332570919c9f0f17f2685af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
0266cb6683c5e32592a7f95737c90989ae3bfa63bc5a769c66ec0aa8beb1c60f
|
b086063b0393d2959b0320b6e2d27a5db7cd945e
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
cc7e4f1295f7e5e0703cee28e6064e0bb3f36a20
|
3d602d80600a3d3981f3363d3d373d3d3d363d73b81a834a2dd2a41a8c740418d53a74021cfb38b65af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73b81a834a2dd2a41a8c740418d53a74021cfb38b65af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
483adf7228b4f32eb919de50a64ed9ef773e8f039d888c4e696c863bc6d76ef3
|
1df09b20f6284b967c0fd719f4f2f8aec3bf5169
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
d824052abd10ab363084115d9d7aae5009b29b60
|
3d602d80600a3d3981f3363d3d373d3d3d363d736558d8a5ec4b9f0028ead6d1cee76a739a31ea8e5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d736558d8a5ec4b9f0028ead6d1cee76a739a31ea8e5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
56ceb405052546d6bf941079de80280df503b3005a6d2e027fc3ae2da04c86bb
|
78e969ce8e804400b8f90c8a23addcf79cc1e06f
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
68b17ab33308b2297518d15999f64ba688d05731
|
3d602d80600a3d3981f3363d3d373d3d3d363d7357ae82ac5d1982430a23e2d1294e3bf7a6430dc95af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7357ae82ac5d1982430a23e2d1294e3bf7a6430dc95af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
a45c8e077bf1ad023bfb105a129a710a513b6ecaa67e210cb4372c8a3006e563
|
b5a96d76a041c874bcad50c3837ef1e30a1e6a54
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
b0287f86f66f4e37e5b6f10ffb20f28c80f62d97
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
19eac1ec94108ebec12272050c87aac9bd9a8630a91983bfe4fef78bdc3b8935
|
2609ceb7f1f85f50a4d2b595a3bb6af04866f2bc
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
fbaf3a08d83ad7b295d8360a75e2818e898e64e1
|
3d602d80600a3d3981f3363d3d373d3d3d363d7322d1a3be57da9e85b6a6edaffd493255cbc7e6905af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7322d1a3be57da9e85b6a6edaffd493255cbc7e6905af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
920e3606b9d9339517ae6b6f7607812a857914bc4dec8c1a479cd400b1bba75a
|
50862a1373204a00b42279f2e54bb2bb11b152e6
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
4e2de23756ecde31bed5f435e295091293518026
|
3d602d80600a3d3981f3363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7332716de33ea7195b2016de930a756bf202ee2edd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
3b6d632d17f8e5ba0403a258d44a963b791a2453582503dadb366c808572be6c
|
148c392fb78f3728e4870f05886b5f907cd0e755
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
c1007a814e941534c4490958c81e172fbb66a2ec
|
3d602d80600a3d3981f3363d3d373d3d3d363d733661d0ab4c10c6215787d3db9b0948f00252dcca5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d733661d0ab4c10c6215787d3db9b0948f00252dcca5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
dc2648d2d16648f0b73c1cbec4da76ccdb57173f7e2bc18fb6f5b58494c7ab7c
|
634ac3fda3deaf662a4f5e7783ac72560a4cbd8a
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
ac94cb0fe40ed788184c60793dc9b1dba49a23ef
|
3d602d80600a3d3981f3363d3d373d3d3d363d73dff3de11361cd5117fa829d9e4aea4b43c303e405af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73dff3de11361cd5117fa829d9e4aea4b43c303e405af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
cc668089caeb632d97ee3cfb6b87f3aedcb2615bf577d150e067886ee0db556e
|
5659eac99d990f2d7bae3122a2f9e3feca0ebe6b
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
df8da970fb2fb9538dec7d2e57f55bb14f0c8ab2
|
3d602d80600a3d3981f3363d3d373d3d3d363d73b1e7505b39130588cd8846446566613b676c5a415af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73b1e7505b39130588cd8846446566613b676c5a415af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
2dbaa2de7a02a73bb7dea65a2b3fa7b14b5f4f789ac7a52a433ac3fa73d3c990
|
e10601fce03b5a3237b603dfd2d04a2fe8320cde
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
3356f955c6121d1a72a324fa1f6289c10730fd43
|
3d602d80600a3d3981f3363d3d373d3d3d363d73810f414946fc7e63ced8e92889263ea73aa9f3f35af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73810f414946fc7e63ced8e92889263ea73aa9f3f35af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,921 |
699ac21352af553cb23d30d1b726380af261ca8e7443ff9c4fa3b8618e7491f5
|
222474b219825e6af1163376a88cf216ba014425fe7c3b1aaf74e33c450e0d04
|
6bc68480d0cef5828192c5093c11ea287758a412
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
836cf6bddbe5f4c188cc0cf2b1fb5998ec8acaf9
|
3d602d80600a3d3981f3363d3d373d3d3d363d73d463d6f44187fc0206f848a7b4df707e998a79ee5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73d463d6f44187fc0206f848a7b4df707e998a79ee5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,923 |
fdbc75817b48ed016bd8242c776378cb706071f6864f9d4a19149c0931029318
|
616c99fae8a1fcaf5f1a56aef2d37a691de3262f2e6687ac2f3a5360dabe8afc
|
1e327b962baee5952f8a9cefd778486920dbc70c
|
1e327b962baee5952f8a9cefd778486920dbc70c
|
36835c82ad1e1a0d525eeec9bd71def985a606dc
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f62b1cbc838b27cab7b4b813902e9a526a40fffb0d36007557f6e75382374384e10a7b62f62d4deec44f9ffde0a59bd57064cb9cee22c0b5bd76008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201b8bfdaff7aef5f56afab635ee739efba1c4e1d5afcc95e89cbcd93510d8841f64736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201b8bfdaff7aef5f56afab635ee739efba1c4e1d5afcc95e89cbcd93510d8841f64736f6c63430008070033
| |
1 | 19,499,926 |
0613ebba1a9116e55123be9f4f761dd710eb3cef2772e5dd209685c41b1e0d51
|
d185704c36cdcb22e84107adb3eef5d06d3fa2301d9ff951e56b0367b1825599
|
2ac8ffa449827c507deea7072edf19edb6c4b1ba
|
612e2daddc89d91409e40f946f9f7cfe422e777e
|
ad95a4aa3383b3df742e9f84e139d08e3a265268
|
3d602d80600a3d3981f3363d3d373d3d3d363d730532fd6e1109756be1503dabe7194b70df0257a75af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730532fd6e1109756be1503dabe7194b70df0257a75af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized != type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(address from, address to, uint256 tokenId) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}\n\n /**\n * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n *\n * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant\n * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such\n * that `ownerOf(tokenId)` is `a`.\n */\n // solhint-disable-next-line func-name-mixedcase\n function __unsafe_increaseBalance(address account, uint256 amount) internal {\n _balances[account] += amount;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[44] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC721Upgradeable.sol\";\nimport \"../../../utils/ContextUpgradeable.sol\";\nimport \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @title ERC721 Burnable Token\n * @dev ERC721 Token that can be burned (destroyed).\n */\nabstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {\n function __ERC721Burnable_init() internal onlyInitializing {\n }\n\n function __ERC721Burnable_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev Burns `tokenId`. See {ERC721-_burn}.\n *\n * Requirements:\n *\n * - The caller must own `tokenId` or be an approved operator.\n */\n function burn(uint256 tokenId) public virtual {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _burn(tokenId);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMathUpgradeable {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/MathUpgradeable.sol\";\nimport \"./math/SignedMathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = MathUpgradeable.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toString(int256 value) internal pure returns (string memory) {\n return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMathUpgradeable.abs(value))));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, MathUpgradeable.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"
},
"@openzeppelin/contracts/utils/ShortStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)\n\npragma solidity ^0.8.8;\n\nimport \"./StorageSlot.sol\";\n\n// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |\n// | length | 0x BB |\ntype ShortString is bytes32;\n\n/**\n * @dev This library provides functions to convert short memory strings\n * into a `ShortString` type that can be used as an immutable variable.\n *\n * Strings of arbitrary length can be optimized using this library if\n * they are short enough (up to 31 bytes) by packing them with their\n * length (1 byte) in a single EVM word (32 bytes). Additionally, a\n * fallback mechanism can be used for every other case.\n *\n * Usage example:\n *\n * ```solidity\n * contract Named {\n * using ShortStrings for *;\n *\n * ShortString private immutable _name;\n * string private _nameFallback;\n *\n * constructor(string memory contractName) {\n * _name = contractName.toShortStringWithFallback(_nameFallback);\n * }\n *\n * function name() external view returns (string memory) {\n * return _name.toStringWithFallback(_nameFallback);\n * }\n * }\n * ```\n */\nlibrary ShortStrings {\n // Used as an identifier for strings longer than 31 bytes.\n bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;\n\n error StringTooLong(string str);\n error InvalidShortString();\n\n /**\n * @dev Encode a string of at most 31 chars into a `ShortString`.\n *\n * This will trigger a `StringTooLong` error is the input string is too long.\n */\n function toShortString(string memory str) internal pure returns (ShortString) {\n bytes memory bstr = bytes(str);\n if (bstr.length > 31) {\n revert StringTooLong(str);\n }\n return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));\n }\n\n /**\n * @dev Decode a `ShortString` back to a \"normal\" string.\n */\n function toString(ShortString sstr) internal pure returns (string memory) {\n uint256 len = byteLength(sstr);\n // using `new string(len)` would work locally but is not memory safe.\n string memory str = new string(32);\n /// @solidity memory-safe-assembly\n assembly {\n mstore(str, len)\n mstore(add(str, 0x20), sstr)\n }\n return str;\n }\n\n /**\n * @dev Return the length of a `ShortString`.\n */\n function byteLength(ShortString sstr) internal pure returns (uint256) {\n uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;\n if (result > 31) {\n revert InvalidShortString();\n }\n return result;\n }\n\n /**\n * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.\n */\n function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {\n if (bytes(value).length < 32) {\n return toShortString(value);\n } else {\n StorageSlot.getStringSlot(store).value = value;\n return ShortString.wrap(_FALLBACK_SENTINEL);\n }\n }\n\n /**\n * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n */\n function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {\n if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {\n return toString(value);\n } else {\n return store;\n }\n }\n\n /**\n * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n *\n * WARNING: This will return the \"byte length\" of the string. This may not reflect the actual length in terms of\n * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.\n */\n function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {\n if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {\n return byteLength(value);\n } else {\n return bytes(store).length;\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/StorageSlot.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}\n"
},
"contracts/collectionTemplates/NFTCollection.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\n\nimport \"../interfaces/internal/INFTCollectionInitializer.sol\";\n\nimport \"../libraries/AddressLibrary.sol\";\n\nimport \"../mixins/collections/CollectionRoyalties.sol\";\nimport \"../mixins/collections/NFTCollectionType.sol\";\nimport \"../mixins/collections/SequentialMintCollection.sol\";\nimport \"../mixins/collections/TokenLimitedCollection.sol\";\nimport \"../mixins/shared/ContractFactory.sol\";\n\nerror NFTCollection_Max_Token_Id_Has_Already_Been_Minted(uint256 maxTokenId);\nerror NFTCollection_Token_CID_Already_Minted();\nerror NFTCollection_Token_CID_Required();\nerror NFTCollection_Token_Creator_Payment_Address_Required();\n\n/**\n * @title A collection of 1:1 NFTs by a single creator.\n * @notice A 10% royalty to the creator is included which may be split with collaborators on a per-NFT basis.\n * @author batu-inal & HardlyDifficult\n */\ncontract NFTCollection is\n INFTCollectionInitializer,\n ContractFactory,\n Initializable,\n ERC165Upgradeable,\n ERC721Upgradeable,\n ERC721BurnableUpgradeable,\n NFTCollectionType,\n SequentialMintCollection,\n TokenLimitedCollection,\n CollectionRoyalties\n{\n using AddressLibrary for address;\n using AddressUpgradeable for address;\n\n /**\n * @notice The baseURI to use for the tokenURI, if undefined then `ipfs://` is used.\n */\n string private baseURI_;\n\n /**\n * @notice Stores hashes minted to prevent duplicates.\n * @dev 0 means not yet minted, set to 1 when minted.\n * For why using uint is better than using bool here:\n * github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.7.3/contracts/security/ReentrancyGuard.sol#L23-L27\n */\n mapping(string => uint256) private cidToMinted;\n\n /**\n * @dev Stores an optional alternate address to receive creator revenue and royalty payments.\n * The target address may be a contract which could split or escrow payments.\n */\n mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress;\n\n /**\n * @dev Stores a CID for each NFT.\n */\n mapping(uint256 => string) private _tokenCIDs;\n\n /**\n * @notice Emitted when the owner changes the base URI to be used for NFTs in this collection.\n * @param baseURI The new base URI to use.\n */\n event BaseURIUpdated(string baseURI);\n\n /**\n * @notice Emitted when a new NFT is minted.\n * @param creator The address of the collection owner at this time this NFT was minted.\n * @param tokenId The tokenId of the newly minted NFT.\n * @param indexedTokenCID The CID of the newly minted NFT, indexed to enable watching for mint events by the tokenCID.\n * @param tokenCID The actual CID of the newly minted NFT.\n */\n event Minted(address indexed creator, uint256 indexed tokenId, string indexed indexedTokenCID, string tokenCID);\n\n /**\n * @notice Emitted when the payment address for creator royalties is set.\n * @param fromPaymentAddress The original address used for royalty payments.\n * @param toPaymentAddress The new address used for royalty payments.\n * @param tokenId The NFT which had the royalty payment address updated.\n */\n event TokenCreatorPaymentAddressSet(\n address indexed fromPaymentAddress,\n address indexed toPaymentAddress,\n uint256 indexed tokenId\n );\n\n /**\n * @notice Initialize the template's immutable variables.\n * @param _contractFactory The factory which will be used to create collection contracts.\n */\n constructor(address _contractFactory) ContractFactory(_contractFactory) NFTCollectionType(NFT_COLLECTION_TYPE) {\n // The template will be initialized by the factory when it's registered for use.\n }\n\n /**\n * @notice Called by the contract factory on creation.\n * @param _creator The creator of this collection.\n * @param _name The collection's `name`.\n * @param _symbol The collection's `symbol`.\n */\n function initialize(\n address payable _creator,\n string calldata _name,\n string calldata _symbol\n ) external initializer onlyContractFactory {\n __ERC721_init(_name, _symbol);\n _initializeSequentialMintCollection(_creator);\n // maxTokenId defaults to 0 but may be assigned later on.\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path.\n * @dev This is only callable by the collection creator/owner.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mint(string calldata tokenCID) external returns (uint256 tokenId) {\n tokenId = _mint(tokenCID);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and approves the provided operator address.\n * @dev This is only callable by the collection creator/owner.\n * It can be used the first time they mint to save having to issue a separate approval\n * transaction before listing the NFT for sale.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param operator The address to set as an approved operator for the creator's account.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintAndApprove(string calldata tokenCID, address operator) external returns (uint256 tokenId) {\n tokenId = _mint(tokenCID);\n setApprovalForAll(operator, true);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and have creator revenue/royalties sent to an alternate address.\n * @dev This is only callable by the collection creator/owner.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param tokenCreatorPaymentAddress The royalty recipient address to use for this NFT.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentAddress(\n string calldata tokenCID,\n address payable tokenCreatorPaymentAddress\n ) public returns (uint256 tokenId) {\n if (tokenCreatorPaymentAddress == address(0)) {\n revert NFTCollection_Token_Creator_Payment_Address_Required();\n }\n tokenId = _mint(tokenCID);\n tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress;\n emit TokenCreatorPaymentAddressSet(address(0), tokenCreatorPaymentAddress, tokenId);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and approves the provided operator address.\n * @dev This is only callable by the collection creator/owner.\n * It can be used the first time they mint to save having to issue a separate approval\n * transaction before listing the NFT for sale.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param tokenCreatorPaymentAddress The royalty recipient address to use for this NFT.\n * @param operator The address to set as an approved operator for the creator's account.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentAddressAndApprove(\n string calldata tokenCID,\n address payable tokenCreatorPaymentAddress,\n address operator\n ) external returns (uint256 tokenId) {\n tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);\n setApprovalForAll(operator, true);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and have creator revenue/royalties sent to an alternate address\n * which is defined by a contract call, typically a proxy contract address representing the payment terms.\n * @dev This is only callable by the collection creator/owner.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param paymentAddressFactory The contract to call which will return the address to use for payments.\n * @param paymentAddressCall The call details to send to the factory provided.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentFactory(\n string calldata tokenCID,\n address paymentAddressFactory,\n bytes calldata paymentAddressCall\n ) public returns (uint256 tokenId) {\n address payable tokenCreatorPaymentAddress = paymentAddressFactory.callAndReturnContractAddress(paymentAddressCall);\n tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and have creator revenue/royalties sent to an alternate address\n * which is defined by a contract call, typically a proxy contract address representing the payment terms.\n * @dev This is only callable by the collection creator/owner.\n * It can be used the first time they mint to save having to issue a separate approval\n * transaction before listing the NFT for sale.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param paymentAddressFactory The contract to call which will return the address to use for payments.\n * @param paymentAddressCall The call details to send to the factory provided.\n * @param operator The address to set as an approved operator for the creator's account.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentFactoryAndApprove(\n string calldata tokenCID,\n address paymentAddressFactory,\n bytes calldata paymentAddressCall,\n address operator\n ) external returns (uint256 tokenId) {\n tokenId = mintWithCreatorPaymentFactory(tokenCID, paymentAddressFactory, paymentAddressCall);\n setApprovalForAll(operator, true);\n }\n\n /**\n * @notice Allows the collection creator to destroy this contract only if\n * no NFTs have been minted yet or the minted NFTs have been burned.\n * @dev Once destructed, a new collection could be deployed to this address (although that's discouraged).\n */\n function selfDestruct() external onlyOwner {\n _selfDestruct();\n }\n\n /**\n * @notice Allows the owner to assign a baseURI to use for the tokenURI instead of the default `ipfs://`.\n * @param baseURIOverride The new base URI to use for all NFTs in this collection.\n */\n function updateBaseURI(string calldata baseURIOverride) external onlyOwner {\n baseURI_ = baseURIOverride;\n\n emit BaseURIUpdated(baseURIOverride);\n }\n\n /**\n * @notice Allows the owner to set a max tokenID.\n * This provides a guarantee to collectors about the limit of this collection contract, if applicable.\n * @dev Once this value has been set, it may be decreased but can never be increased.\n * This max may be more than the final `totalSupply` if 1 or more tokens were burned.\n * @param _maxTokenId The max tokenId to set, all NFTs must have a tokenId less than or equal to this value.\n */\n function updateMaxTokenId(uint32 _maxTokenId) external onlyOwner {\n _updateMaxTokenId(_maxTokenId);\n }\n\n /**\n * @inheritdoc ERC721Upgradeable\n * @dev The function here asserts `onlyOwner` while the super confirms ownership.\n */\n function _burn(uint256 tokenId) internal override(ERC721Upgradeable, SequentialMintCollection) onlyOwner {\n delete cidToMinted[_tokenCIDs[tokenId]];\n delete tokenIdToCreatorPaymentAddress[tokenId];\n delete _tokenCIDs[tokenId];\n super._burn(tokenId);\n }\n\n function _mint(string calldata tokenCID) private onlyOwner returns (uint256 tokenId) {\n if (bytes(tokenCID).length == 0) {\n revert NFTCollection_Token_CID_Required();\n }\n if (cidToMinted[tokenCID] != 0) {\n revert NFTCollection_Token_CID_Already_Minted();\n }\n // If the mint will exceed uint32, the addition here will overflow. But it's not realistic to mint that many tokens.\n tokenId = ++latestTokenId;\n if (maxTokenId != 0 && tokenId > maxTokenId) {\n revert NFTCollection_Max_Token_Id_Has_Already_Been_Minted(maxTokenId);\n }\n cidToMinted[tokenCID] = 1;\n _tokenCIDs[tokenId] = tokenCID;\n _safeMint(msg.sender, tokenId);\n emit Minted(msg.sender, tokenId, tokenCID, tokenCID);\n }\n\n /**\n * @notice The base URI used for all NFTs in this collection.\n * @dev The `tokenCID` is appended to this to obtain an NFT's `tokenURI`.\n * e.g. The URI for a token with the `tokenCID`: \"foo\" and `baseURI`: \"ipfs://\" is \"ipfs://foo\".\n * @return uri The base URI used by this collection.\n */\n function baseURI() external view returns (string memory uri) {\n uri = _baseURI();\n }\n\n /**\n * @notice Checks if the creator has already minted a given NFT using this collection contract.\n * @param tokenCID The CID to check for.\n * @return hasBeenMinted True if the creator has already minted an NFT with this CID.\n */\n function getHasMintedCID(string calldata tokenCID) external view returns (bool hasBeenMinted) {\n hasBeenMinted = cidToMinted[tokenCID] != 0;\n }\n\n /**\n * @inheritdoc CollectionRoyalties\n */\n function getTokenCreatorPaymentAddress(\n uint256 tokenId\n ) public view override returns (address payable creatorPaymentAddress) {\n creatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId];\n if (creatorPaymentAddress == address(0)) {\n creatorPaymentAddress = owner;\n }\n }\n\n /**\n * @inheritdoc IERC165Upgradeable\n */\n function supportsInterface(\n bytes4 interfaceId\n )\n public\n view\n override(ERC165Upgradeable, ERC721Upgradeable, NFTCollectionType, CollectionRoyalties)\n returns (bool interfaceSupported)\n {\n interfaceSupported = super.supportsInterface(interfaceId);\n }\n\n /**\n * @inheritdoc IERC721MetadataUpgradeable\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory uri) {\n _requireMinted(tokenId);\n\n uri = string.concat(_baseURI(), _tokenCIDs[tokenId]);\n }\n\n function _baseURI() internal view override returns (string memory uri) {\n uri = baseURI_;\n if (bytes(uri).length == 0) {\n uri = \"ipfs://\";\n }\n }\n}\n"
},
"contracts/interfaces/internal/INFTCollectionInitializer.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @title Declares the interface for initializing an NFTCollection contract.\n * @author batu-inal & HardlyDifficult\n */\ninterface INFTCollectionInitializer {\n function initialize(address payable _creator, string memory _name, string memory _symbol) external;\n}\n"
},
"contracts/interfaces/internal/INFTCollectionType.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @title Declares the type of the collection contract.\n * @dev This interface is declared as an ERC-165 interface.\n * @author reggieag\n */\ninterface INFTCollectionType {\n function getNFTCollectionType() external view returns (string memory collectionType);\n}\n"
},
"contracts/interfaces/standards/royalties/IGetFees.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @notice An interface for communicating fees to 3rd party marketplaces.\n * @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3\n */\ninterface IGetFees {\n /**\n * @notice Get the recipient addresses to which creator royalties should be sent.\n * @dev The expected royalty amounts are communicated with `getFeeBps`.\n * @param tokenId The ID of the NFT to get royalties for.\n * @return recipients An array of addresses to which royalties should be sent.\n */\n function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory recipients);\n\n /**\n * @notice Get the creator royalty amounts to be sent to each recipient, in basis points.\n * @dev The expected recipients are communicated with `getFeeRecipients`.\n * @param tokenId The ID of the NFT to get royalties for.\n * @return royaltiesInBasisPoints The array of fees to be sent to each recipient, in basis points.\n */\n function getFeeBps(uint256 tokenId) external view returns (uint256[] memory royaltiesInBasisPoints);\n}\n"
},
"contracts/interfaces/standards/royalties/IGetRoyalties.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\ninterface IGetRoyalties {\n /**\n * @notice Get the creator royalties to be sent.\n * @dev The data is the same as when calling `getFeeRecipients` and `getFeeBps` separately.\n * @param tokenId The ID of the NFT to get royalties for.\n * @return recipients An array of addresses to which royalties should be sent.\n * @return royaltiesInBasisPoints The array of fees to be sent to each recipient, in basis points.\n */\n function getRoyalties(\n uint256 tokenId\n ) external view returns (address payable[] memory recipients, uint256[] memory royaltiesInBasisPoints);\n}\n"
},
"contracts/interfaces/standards/royalties/IRoyaltyInfo.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @notice Interface for EIP-2981: NFT Royalty Standard.\n * For more see: https://eips.ethereum.org/EIPS/eip-2981.\n */\ninterface IRoyaltyInfo {\n /**\n * @notice Get the creator royalties to be sent.\n * @param tokenId The ID of the NFT to get royalties for.\n * @param salePrice The total price of the sale.\n * @return receiver The address to which royalties should be sent.\n * @return royaltyAmount The total amount that should be sent to the `receiver`.\n */\n function royaltyInfo(\n uint256 tokenId,\n uint256 salePrice\n ) external view returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"contracts/interfaces/standards/royalties/ITokenCreator.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\ninterface ITokenCreator {\n /**\n * @notice Returns the creator of this NFT collection.\n * @param tokenId The ID of the NFT to get the creator payment address for.\n * @return creator The creator of this collection.\n */\n function tokenCreator(uint256 tokenId) external view returns (address payable creator);\n}\n"
},
"contracts/libraries/AddressLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\n\nstruct CallWithoutValue {\n address target;\n bytes callData;\n}\n\nerror AddressLibrary_Proxy_Call_Did_Not_Return_A_Contract(address addressReturned);\n\n/**\n * @title A library for address helpers not already covered by the OZ library.\n * @author batu-inal & HardlyDifficult\n */\nlibrary AddressLibrary {\n using AddressUpgradeable for address;\n using AddressUpgradeable for address payable;\n\n /**\n * @notice Calls an external contract with arbitrary data and parse the return value into an address.\n * @param externalContract The address of the contract to call.\n * @param callData The data to send to the contract.\n * @return contractAddress The address of the contract returned by the call.\n */\n function callAndReturnContractAddress(\n address externalContract,\n bytes calldata callData\n ) internal returns (address payable contractAddress) {\n bytes memory returnData = externalContract.functionCall(callData);\n contractAddress = abi.decode(returnData, (address));\n if (!contractAddress.isContract()) {\n revert AddressLibrary_Proxy_Call_Did_Not_Return_A_Contract(contractAddress);\n }\n }\n\n function callAndReturnContractAddress(\n CallWithoutValue calldata call\n ) internal returns (address payable contractAddress) {\n contractAddress = callAndReturnContractAddress(call.target, call.callData);\n }\n}\n"
},
"contracts/mixins/collections/CollectionRoyalties.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\n\nimport \"../../interfaces/standards/royalties/IGetFees.sol\";\nimport \"../../interfaces/standards/royalties/IGetRoyalties.sol\";\nimport \"../../interfaces/standards/royalties/IRoyaltyInfo.sol\";\nimport \"../../interfaces/standards/royalties/ITokenCreator.sol\";\n\nimport \"../shared/Constants.sol\";\n\n/**\n * @title Defines various royalty APIs for broad marketplace support.\n * @author batu-inal & HardlyDifficult\n */\nabstract contract CollectionRoyalties is IGetRoyalties, IGetFees, IRoyaltyInfo, ITokenCreator, ERC165Upgradeable {\n /**\n * @inheritdoc IGetFees\n */\n function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory recipients) {\n recipients = new address payable[](1);\n recipients[0] = getTokenCreatorPaymentAddress(tokenId);\n }\n\n /**\n * @inheritdoc IGetFees\n * @dev The tokenId param is ignored since all NFTs return the same value.\n */\n function getFeeBps(uint256 /* tokenId */) external pure returns (uint256[] memory royaltiesInBasisPoints) {\n royaltiesInBasisPoints = new uint256[](1);\n royaltiesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;\n }\n\n /**\n * @inheritdoc IGetRoyalties\n */\n function getRoyalties(\n uint256 tokenId\n ) external view returns (address payable[] memory recipients, uint256[] memory royaltiesInBasisPoints) {\n recipients = new address payable[](1);\n recipients[0] = getTokenCreatorPaymentAddress(tokenId);\n royaltiesInBasisPoints = new uint256[](1);\n royaltiesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;\n }\n\n /**\n * @notice The address to pay the creator proceeds/royalties for the collection.\n * @param tokenId The ID of the NFT to get the creator payment address for.\n * @return creatorPaymentAddress The address to which royalties should be paid.\n */\n function getTokenCreatorPaymentAddress(\n uint256 tokenId\n ) public view virtual returns (address payable creatorPaymentAddress);\n\n /**\n * @inheritdoc IRoyaltyInfo\n */\n function royaltyInfo(\n uint256 tokenId,\n uint256 salePrice\n ) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = getTokenCreatorPaymentAddress(tokenId);\n unchecked {\n royaltyAmount = salePrice / ROYALTY_RATIO;\n }\n }\n\n /**\n * @inheritdoc IERC165Upgradeable\n * @dev Checks the supported royalty interfaces.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool interfaceSupported) {\n interfaceSupported = (interfaceId == type(IRoyaltyInfo).interfaceId ||\n interfaceId == type(ITokenCreator).interfaceId ||\n interfaceId == type(IGetRoyalties).interfaceId ||\n interfaceId == type(IGetFees).interfaceId ||\n super.supportsInterface(interfaceId));\n }\n}\n"
},
"contracts/mixins/collections/NFTCollectionType.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/ShortStrings.sol\";\n\nimport \"../../interfaces/internal/INFTCollectionType.sol\";\n\n/**\n * @title A mixin to add the NFTCollectionType interface to a contract.\n * @author HardlyDifficult & reggieag\n */\nabstract contract NFTCollectionType is INFTCollectionType, ERC165Upgradeable {\n using ShortStrings for string;\n using ShortStrings for ShortString;\n\n ShortString private immutable _collectionTypeName;\n\n constructor(string memory collectionTypeName) {\n _collectionTypeName = collectionTypeName.toShortString();\n }\n\n /**\n * @notice Returns a name of the type of collection this contract represents.\n * @return collectionType The collection type.\n */\n function getNFTCollectionType() external view returns (string memory collectionType) {\n collectionType = _collectionTypeName.toString();\n }\n\n /**\n * @inheritdoc IERC165Upgradeable\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool interfaceSupported) {\n interfaceSupported = interfaceId == type(INFTCollectionType).interfaceId || super.supportsInterface(interfaceId);\n }\n}\n"
},
"contracts/mixins/collections/SequentialMintCollection.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol\";\n\nimport \"../../interfaces/standards/royalties/ITokenCreator.sol\";\n\nerror SequentialMintCollection_Caller_Is_Not_Owner(address owner);\nerror SequentialMintCollection_Minted_NFTs_Must_Be_Burned_First(uint256 totalSupply);\n\n/**\n * @title Extends the OZ ERC721 implementation for collections which mint sequential token IDs.\n * @author batu-inal & HardlyDifficult\n */\nabstract contract SequentialMintCollection is ITokenCreator, ERC721BurnableUpgradeable {\n /****** Slot 0 (after inheritance) ******/\n /**\n * @notice The creator/owner of this NFT collection.\n * @dev This is the default royalty recipient if a different `paymentAddress` was not provided.\n * @return The collection's creator/owner address.\n */\n address payable public owner;\n\n /**\n * @notice The tokenId of the most recently created NFT.\n * @dev Minting starts at tokenId 1. Each mint will use this value + 1.\n * @return The most recently minted tokenId, or 0 if no NFTs have been minted yet.\n */\n uint32 public latestTokenId;\n\n /**\n * @notice Tracks how many tokens have been burned.\n * @dev This number is used to calculate the total supply efficiently.\n */\n uint32 private burnCounter;\n\n // 32-bits free space\n\n /****** End of storage ******/\n\n /**\n * @notice Emitted when this collection is self destructed by the creator/owner/admin.\n * @param admin The account which requested this contract be self destructed.\n */\n event SelfDestruct(address indexed admin);\n\n modifier onlyOwner() {\n if (msg.sender != owner) {\n revert SequentialMintCollection_Caller_Is_Not_Owner(owner);\n }\n _;\n }\n\n function _initializeSequentialMintCollection(address payable _creator) internal {\n owner = _creator;\n }\n\n /**\n * @notice Allows the collection owner to destroy this contract only if\n * no NFTs have been minted yet or the minted NFTs have been burned.\n */\n function _selfDestruct() internal {\n if (totalSupply() != 0) {\n revert SequentialMintCollection_Minted_NFTs_Must_Be_Burned_First(totalSupply());\n }\n\n emit SelfDestruct(msg.sender);\n selfdestruct(payable(msg.sender));\n }\n\n function _burn(uint256 tokenId) internal virtual override {\n unchecked {\n // Number of burned tokens cannot exceed latestTokenId which is the same size.\n ++burnCounter;\n }\n super._burn(tokenId);\n }\n\n /**\n * @inheritdoc ITokenCreator\n * @dev The tokenId param is ignored since all NFTs return the same value.\n */\n function tokenCreator(uint256 /* tokenId */) external view returns (address payable creator) {\n creator = owner;\n }\n\n /**\n * @notice Returns the total amount of tokens stored by the contract.\n * @dev From the ERC-721 enumerable standard.\n * @return supply The total number of NFTs tracked by this contract.\n */\n function totalSupply() public view returns (uint256 supply) {\n unchecked {\n // Number of tokens minted is always >= burned tokens.\n supply = latestTokenId - burnCounter;\n }\n }\n}\n"
},
"contracts/mixins/collections/TokenLimitedCollection.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"./SequentialMintCollection.sol\";\n\nerror TokenLimitedCollection_Max_Token_Id_May_Not_Be_Cleared(uint256 currentMaxTokenId);\nerror TokenLimitedCollection_Max_Token_Id_May_Not_Increase(uint256 currentMaxTokenId);\nerror TokenLimitedCollection_Max_Token_Id_Must_Be_Greater_Than_Current_Minted_Count(uint256 currentMintedCount);\nerror TokenLimitedCollection_Max_Token_Id_Must_Not_Be_Zero();\n\n/**\n * @title Defines an upper limit on the number of tokens which may be minted by this collection.\n * @author HardlyDifficult\n */\nabstract contract TokenLimitedCollection is SequentialMintCollection {\n /**\n * @notice The max tokenId which can be minted.\n * @dev This max may be less than the final `totalSupply` if 1 or more tokens were burned.\n * @return The max tokenId which can be minted.\n */\n uint32 public maxTokenId;\n\n /**\n * @notice Emitted when the max tokenId supported by this collection is updated.\n * @param maxTokenId The new max tokenId. All NFTs in this collection will have a tokenId less than\n * or equal to this value.\n */\n event MaxTokenIdUpdated(uint256 indexed maxTokenId);\n\n function _initializeTokenLimitedCollection(uint32 _maxTokenId) internal {\n if (_maxTokenId == 0) {\n // When 0 is desired, the collection may choose to simply not call this initializer.\n revert TokenLimitedCollection_Max_Token_Id_Must_Not_Be_Zero();\n }\n\n maxTokenId = _maxTokenId;\n }\n\n /**\n * @notice Allows the owner to set a max tokenID.\n * This provides a guarantee to collectors about the limit of this collection contract, if applicable.\n * @dev Once this value has been set, it may be decreased but can never be increased.\n * @param _maxTokenId The max tokenId to set, all NFTs must have a tokenId less than or equal to this value.\n */\n function _updateMaxTokenId(uint32 _maxTokenId) internal {\n if (_maxTokenId == 0) {\n revert TokenLimitedCollection_Max_Token_Id_May_Not_Be_Cleared(maxTokenId);\n }\n if (maxTokenId != 0 && _maxTokenId >= maxTokenId) {\n revert TokenLimitedCollection_Max_Token_Id_May_Not_Increase(maxTokenId);\n }\n if (latestTokenId > _maxTokenId) {\n revert TokenLimitedCollection_Max_Token_Id_Must_Be_Greater_Than_Current_Minted_Count(latestTokenId);\n }\n\n maxTokenId = _maxTokenId;\n emit MaxTokenIdUpdated(_maxTokenId);\n }\n}\n"
},
"contracts/mixins/shared/Constants.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/// Constant values shared across mixins.\n\n/**\n * @dev 100% in basis points.\n */\nuint256 constant BASIS_POINTS = 10_000;\n\n/**\n * @dev The default admin role defined by OZ ACL modules.\n */\nbytes32 constant DEFAULT_ADMIN_ROLE = 0x00;\n\n////////////////////////////////////////////////////////////////\n// Royalties & Take Rates\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev The max take rate an exhibition can have.\n */\nuint256 constant MAX_EXHIBITION_TAKE_RATE = 5_000;\n\n/**\n * @dev Cap the number of royalty recipients.\n * A cap is required to ensure gas costs are not too high when a sale is settled.\n */\nuint256 constant MAX_ROYALTY_RECIPIENTS = 5;\n\n/**\n * @dev Default royalty cut paid out on secondary sales.\n * Set to 10% of the secondary sale.\n */\nuint96 constant ROYALTY_IN_BASIS_POINTS = 1_000;\n\n/**\n * @dev Reward paid to referrers when a sale is made.\n * Set to 1% of the sale amount. This 1% is deducted from the protocol fee.\n */\nuint96 constant BUY_REFERRER_IN_BASIS_POINTS = 100;\n\n/**\n * @dev 10%, expressed as a denominator for more efficient calculations.\n */\nuint256 constant ROYALTY_RATIO = BASIS_POINTS / ROYALTY_IN_BASIS_POINTS;\n\n/**\n * @dev 1%, expressed as a denominator for more efficient calculations.\n */\nuint256 constant BUY_REFERRER_RATIO = BASIS_POINTS / BUY_REFERRER_IN_BASIS_POINTS;\n\n////////////////////////////////////////////////////////////////\n// Gas Limits\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev The gas limit used when making external read-only calls.\n * This helps to ensure that external calls does not prevent the market from executing.\n */\nuint256 constant READ_ONLY_GAS_LIMIT = 40_000;\n\n/**\n * @dev The gas limit to send ETH to multiple recipients, enough for a 5-way split.\n */\nuint256 constant SEND_VALUE_GAS_LIMIT_MULTIPLE_RECIPIENTS = 210_000;\n\n/**\n * @dev The gas limit to send ETH to a single recipient, enough for a contract with a simple receiver.\n */\nuint256 constant SEND_VALUE_GAS_LIMIT_SINGLE_RECIPIENT = 20_000;\n\n////////////////////////////////////////////////////////////////\n// Collection Type Names\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev The NFT collection type.\n */\nstring constant NFT_COLLECTION_TYPE = \"NFT Collection\";\n\n/**\n * @dev The NFT drop collection type.\n */\nstring constant NFT_DROP_COLLECTION_TYPE = \"NFT Drop Collection\";\n\n/**\n * @dev The NFT timed edition collection type.\n */\nstring constant NFT_TIMED_EDITION_COLLECTION_TYPE = \"NFT Timed Edition Collection\";\n\n/**\n * @dev The NFT limited edition collection type.\n */\nstring constant NFT_LIMITED_EDITION_COLLECTION_TYPE = \"NFT Limited Edition Collection\";\n\n////////////////////////////////////////////////////////////////\n// Business Logic\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev Limits scheduled start/end times to be less than 2 years in the future.\n */\nuint256 constant MAX_SCHEDULED_TIME_IN_THE_FUTURE = 365 days * 2;\n\n/**\n * @dev The minimum increase of 10% required when making an offer or placing a bid.\n */\nuint256 constant MIN_PERCENT_INCREMENT_DENOMINATOR = BASIS_POINTS / 1_000;\n\n/**\n * @dev Protocol fee for edition mints in basis points.\n */\nuint256 constant EDITION_PROTOCOL_FEE_IN_BASIS_POINTS = 500;\n\n/**\n * @dev Hash of the edition type names.\n * This is precalculated in order to save gas on use.\n * `keccak256(abi.encodePacked(NFT_TIMED_EDITION_COLLECTION_TYPE))`\n */\nbytes32 constant timedEditionTypeHash = 0xee2afa3f960e108aca17013728aafa363a0f4485661d9b6f41c6b4ddb55008ee;\n\nbytes32 constant limitedEditionTypeHash = 0x7df1f68d01ab1a6ee0448a4c3fbda832177331ff72c471b12b0051c96742eef5;\n"
},
"contracts/mixins/shared/ContractFactory.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\n\nerror ContractFactory_Only_Callable_By_Factory_Contract(address contractFactory);\nerror ContractFactory_Factory_Is_Not_A_Contract();\n\n/**\n * @title Stores a reference to the factory which is used to create contract proxies.\n * @author batu-inal & HardlyDifficult\n */\nabstract contract ContractFactory {\n using AddressUpgradeable for address;\n\n /**\n * @notice The address of the factory which was used to create this contract.\n * @return The factory contract address.\n */\n address public immutable contractFactory;\n\n modifier onlyContractFactory() {\n if (msg.sender != contractFactory) {\n revert ContractFactory_Only_Callable_By_Factory_Contract(contractFactory);\n }\n _;\n }\n\n /**\n * @notice Initialize the template's immutable variables.\n * @param _contractFactory The factory which will be used to create these contracts.\n */\n constructor(address _contractFactory) {\n if (!_contractFactory.isContract()) {\n revert ContractFactory_Factory_Is_Not_A_Contract();\n }\n contractFactory = _contractFactory;\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 1337000
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
},
"libraries": {}
}
}}
|
1 | 19,499,930 |
2d89fa99eb07fa5acbbc6a6224a4364ff09d61578b8d551e094bf032601f78ef
|
d9f75fced35277709e630de961f30a7a020b32f595d5fbf9ea5a1a6c82e224ea
|
8c4b7870fc7dff2cb1e854858533ceddaf3eebf4
|
9a0d63911620f7fc15c3c020edbe4d7267ea3e4d
|
0f232cca605322685abca4b208cb81afafc7e869
|
3d602d80600a3d3981f3363d3d373d3d3d363d73e8e847cf573fc8ed75621660a36affd18c543d7e5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73e8e847cf573fc8ed75621660a36affd18c543d7e5af43d82803e903d91602b57fd5bf3
|
{"ERC20Interface.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.7.5;\n\n/**\n * Contract that exposes the needed erc20 token functions\n */\n\nabstract contract ERC20Interface {\n // Send _value amount of tokens to address _to\n function transfer(address _to, uint256 _value)\n public\n virtual\n returns (bool success);\n\n // Get the account balance of another account with address _owner\n function balanceOf(address _owner)\n public\n virtual\n view\n returns (uint256 balance);\n}\n"},"Forwarder.sol":{"content":"// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.7.5;\nimport \u0027./TransferHelper.sol\u0027;\nimport \u0027./ERC20Interface.sol\u0027;\n\n/**\n * Contract that will forward any incoming Ether to the creator of the contract\n *\n */\ncontract Forwarder {\n // Address to which any funds sent to this contract will be forwarded\n address public parentAddress;\n event ForwarderDeposited(address from, uint256 value, bytes data);\n\n /**\n * Initialize the contract, and sets the destination address to that of the creator\n */\n function init(address _parentAddress) external onlyUninitialized {\n parentAddress = _parentAddress;\n uint256 value = address(this).balance;\n\n if (value == 0) {\n return;\n }\n\n (bool success, ) = parentAddress.call{ value: value }(\u0027\u0027);\n require(success, \u0027Flush failed\u0027);\n // NOTE: since we are forwarding on initialization,\n // we don\u0027t have the context of the original sender.\n // We still emit an event about the forwarding but set\n // the sender to the forwarder itself\n emit ForwarderDeposited(address(this), value, msg.data);\n }\n\n /**\n * Modifier that will execute internal code block only if the sender is the parent address\n */\n modifier onlyParent {\n require(msg.sender == parentAddress, \u0027Only Parent\u0027);\n _;\n }\n\n /**\n * Modifier that will execute internal code block only if the contract has not been initialized yet\n */\n modifier onlyUninitialized {\n require(parentAddress == address(0x0), \u0027Already initialized\u0027);\n _;\n }\n\n /**\n * Default function; Gets called when data is sent but does not match any other function\n */\n fallback() external payable {\n flush();\n }\n\n /**\n * Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address\n */\n receive() external payable {\n flush();\n }\n\n /**\n * Execute a token transfer of the full balance from the forwarder token to the parent address\n * @param tokenContractAddress the address of the erc20 token contract\n */\n function flushTokens(address tokenContractAddress) external onlyParent {\n ERC20Interface instance = ERC20Interface(tokenContractAddress);\n address forwarderAddress = address(this);\n uint256 forwarderBalance = instance.balanceOf(forwarderAddress);\n if (forwarderBalance == 0) {\n return;\n }\n\n TransferHelper.safeTransfer(\n tokenContractAddress,\n parentAddress,\n forwarderBalance\n );\n }\n\n /**\n * Flush the entire balance of the contract to the parent address.\n */\n function flush() public {\n uint256 value = address(this).balance;\n\n if (value == 0) {\n return;\n }\n\n (bool success, ) = parentAddress.call{ value: value }(\u0027\u0027);\n require(success, \u0027Flush failed\u0027);\n emit ForwarderDeposited(msg.sender, value, msg.data);\n }\n}\n"},"TransferHelper.sol":{"content":"// SPDX-License-Identifier: Apache-2.0\n\npragma solidity \u003e=0.7.5;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeApprove(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027approve(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeApprove: approve failed\u0027\n );\n }\n\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::safeTransfer: transfer failed\u0027\n );\n }\n\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 value\n ) internal {\n // bytes4(keccak256(bytes(\u0027transferFrom(address,address,uint256)\u0027)));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n require(\n success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))),\n \u0027TransferHelper::transferFrom: transferFrom failed\u0027\n );\n }\n\n function safeTransferETH(address to, uint256 value) internal {\n (bool success, ) = to.call{value: value}(new bytes(0));\n require(success, \u0027TransferHelper::safeTransferETH: ETH transfer failed\u0027);\n }\n}\n"},"WalletSimple.sol":{"content":"// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.7.5;\nimport \u0027./TransferHelper.sol\u0027;\nimport \u0027./Forwarder.sol\u0027;\nimport \u0027./ERC20Interface.sol\u0027;\n\n/**\n *\n * WalletSimple\n * ============\n *\n * Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.\n * Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.\n *\n * The first signature is created on the operation hash (see Data Formats) and passed to sendMultiSig/sendMultiSigToken\n * The signer is determined by verifyMultiSig().\n *\n * The second signature is created by the submitter of the transaction and determined by msg.signer.\n *\n * Data Formats\n * ============\n *\n * The signature is created with ethereumjs-util.ecsign(operationHash).\n * Like the eth_sign RPC call, it packs the values as a 65-byte array of [r, s, v].\n * Unlike eth_sign, the message is not prefixed.\n *\n * The operationHash the result of keccak256(prefix, toAddress, value, data, expireTime).\n * For ether transactions, `prefix` is \"ETHER\".\n * For token transaction, `prefix` is \"ERC20\" and `data` is the tokenContractAddress.\n *\n *\n */\ncontract WalletSimple {\n // Events\n event Deposited(address from, uint256 value, bytes data);\n event SafeModeActivated(address msgSender);\n event Transacted(\n address msgSender, // Address of the sender of the message initiating the transaction\n address otherSigner, // Address of the signer (second signature) used to initiate the transaction\n bytes32 operation, // Operation hash (see Data Formats)\n address toAddress, // The address the transaction was sent to\n uint256 value, // Amount of Wei sent to the address\n bytes data // Data sent when invoking the transaction\n );\n\n event BatchTransfer(address sender, address recipient, uint256 value);\n // this event shows the other signer and the operation hash that they signed\n // specific batch transfer events are emitted in Batcher\n event BatchTransacted(\n address msgSender, // Address of the sender of the message initiating the transaction\n address otherSigner, // Address of the signer (second signature) used to initiate the transaction\n bytes32 operation // Operation hash (see Data Formats)\n );\n\n // Public fields\n mapping(address =\u003e bool) public signers; // The addresses that can co-sign transactions on the wallet\n bool public safeMode = false; // When active, wallet may only send to signer addresses\n bool public initialized = false; // True if the contract has been initialized\n\n // Internal fields\n uint256 private constant MAX_SEQUENCE_ID_INCREASE = 10000;\n uint256 constant SEQUENCE_ID_WINDOW_SIZE = 10;\n uint256[SEQUENCE_ID_WINDOW_SIZE] recentSequenceIds;\n\n /**\n * Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.\n * 2 signers will be required to send a transaction from this wallet.\n * Note: The sender is NOT automatically added to the list of signers.\n * Signers CANNOT be changed once they are set\n *\n * @param allowedSigners An array of signers on the wallet\n */\n function init(address[] calldata allowedSigners) external onlyUninitialized {\n require(allowedSigners.length == 3, \u0027Invalid number of signers\u0027);\n\n for (uint8 i = 0; i \u003c allowedSigners.length; i++) {\n require(allowedSigners[i] != address(0), \u0027Invalid signer\u0027);\n signers[allowedSigners[i]] = true;\n }\n initialized = true;\n }\n\n /**\n * Get the network identifier that signers must sign over\n * This provides protection signatures being replayed on other chains\n * This must be a virtual function because chain-specific contracts will need\n * to override with their own network ids. It also can\u0027t be a field\n * to allow this contract to be used by proxy with delegatecall, which will\n * not pick up on state variables\n */\n function getNetworkId() internal virtual pure returns (string memory) {\n return \u0027ETHER\u0027;\n }\n\n /**\n * Get the network identifier that signers must sign over for token transfers\n * This provides protection signatures being replayed on other chains\n * This must be a virtual function because chain-specific contracts will need\n * to override with their own network ids. It also can\u0027t be a field\n * to allow this contract to be used by proxy with delegatecall, which will\n * not pick up on state variables\n */\n function getTokenNetworkId() internal virtual pure returns (string memory) {\n return \u0027ERC20\u0027;\n }\n\n /**\n * Get the network identifier that signers must sign over for batch transfers\n * This provides protection signatures being replayed on other chains\n * This must be a virtual function because chain-specific contracts will need\n * to override with their own network ids. It also can\u0027t be a field\n * to allow this contract to be used by proxy with delegatecall, which will\n * not pick up on state variables\n */\n function getBatchNetworkId() internal virtual pure returns (string memory) {\n return \u0027ETHER-Batch\u0027;\n }\n\n /**\n * Determine if an address is a signer on this wallet\n * @param signer address to check\n * returns boolean indicating whether address is signer or not\n */\n function isSigner(address signer) public view returns (bool) {\n return signers[signer];\n }\n\n /**\n * Modifier that will execute internal code block only if the sender is an authorized signer on this wallet\n */\n modifier onlySigner {\n require(isSigner(msg.sender), \u0027Non-signer in onlySigner method\u0027);\n _;\n }\n\n /**\n * Modifier that will execute internal code block only if the contract has not been initialized yet\n */\n modifier onlyUninitialized {\n require(!initialized, \u0027Contract already initialized\u0027);\n _;\n }\n\n /**\n * Gets called when a transaction is received with data that does not match any other method\n */\n fallback() external payable {\n if (msg.value \u003e 0) {\n // Fire deposited event if we are receiving funds\n Deposited(msg.sender, msg.value, msg.data);\n }\n }\n\n /**\n * Gets called when a transaction is received with ether and no data\n */\n receive() external payable {\n if (msg.value \u003e 0) {\n // Fire deposited event if we are receiving funds\n Deposited(msg.sender, msg.value, msg.data);\n }\n }\n\n /**\n * Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.\n * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.\n *\n * @param toAddress the destination address to send an outgoing transaction\n * @param value the amount in Wei to be sent\n * @param data the data to send to the toAddress when invoking the transaction\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\n * @param signature see Data Formats\n */\n function sendMultiSig(\n address toAddress,\n uint256 value,\n bytes calldata data,\n uint256 expireTime,\n uint256 sequenceId,\n bytes calldata signature\n ) external onlySigner {\n // Verify the other signer\n bytes32 operationHash = keccak256(\n abi.encodePacked(\n getNetworkId(),\n toAddress,\n value,\n data,\n expireTime,\n sequenceId\n )\n );\n\n address otherSigner = verifyMultiSig(\n toAddress,\n operationHash,\n signature,\n expireTime,\n sequenceId\n );\n\n // Success, send the transaction\n (bool success, ) = toAddress.call{ value: value }(data);\n require(success, \u0027Call execution failed\u0027);\n\n emit Transacted(\n msg.sender,\n otherSigner,\n operationHash,\n toAddress,\n value,\n data\n );\n }\n\n /**\n * Execute a batched multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.\n * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.\n * The recipients and values to send are encoded in two arrays, where for index i, recipients[i] will be sent values[i].\n *\n * @param recipients The list of recipients to send to\n * @param values The list of values to send to\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\n * @param signature see Data Formats\n */\n function sendMultiSigBatch(\n address[] calldata recipients,\n uint256[] calldata values,\n uint256 expireTime,\n uint256 sequenceId,\n bytes calldata signature\n ) external onlySigner {\n require(recipients.length != 0, \u0027Not enough recipients\u0027);\n require(\n recipients.length == values.length,\n \u0027Unequal recipients and values\u0027\n );\n require(recipients.length \u003c 256, \u0027Too many recipients, max 255\u0027);\n\n // Verify the other signer\n bytes32 operationHash = keccak256(\n abi.encodePacked(\n getBatchNetworkId(),\n recipients,\n values,\n expireTime,\n sequenceId\n )\n );\n\n // the first parameter (toAddress) is used to ensure transactions in safe mode only go to a signer\n // if in safe mode, we should use normal sendMultiSig to recover, so this check will always fail if in safe mode\n require(!safeMode, \u0027Batch in safe mode\u0027);\n address otherSigner = verifyMultiSig(\n address(0x0),\n operationHash,\n signature,\n expireTime,\n sequenceId\n );\n\n batchTransfer(recipients, values);\n emit BatchTransacted(msg.sender, otherSigner, operationHash);\n }\n\n /**\n * Transfer funds in a batch to each of recipients\n * @param recipients The list of recipients to send to\n * @param values The list of values to send to recipients.\n * The recipient with index i in recipients array will be sent values[i].\n * Thus, recipients and values must be the same length\n */\n function batchTransfer(\n address[] calldata recipients,\n uint256[] calldata values\n ) internal {\n for (uint256 i = 0; i \u003c recipients.length; i++) {\n require(address(this).balance \u003e= values[i], \u0027Insufficient funds\u0027);\n\n (bool success, ) = recipients[i].call{ value: values[i] }(\u0027\u0027);\n require(success, \u0027Call failed\u0027);\n\n emit BatchTransfer(msg.sender, recipients[i], values[i]);\n }\n }\n\n /**\n * Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.\n * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.\n *\n * @param toAddress the destination address to send an outgoing transaction\n * @param value the amount in tokens to be sent\n * @param tokenContractAddress the address of the erc20 token contract\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\n * @param signature see Data Formats\n */\n function sendMultiSigToken(\n address toAddress,\n uint256 value,\n address tokenContractAddress,\n uint256 expireTime,\n uint256 sequenceId,\n bytes calldata signature\n ) external onlySigner {\n // Verify the other signer\n bytes32 operationHash = keccak256(\n abi.encodePacked(\n getTokenNetworkId(),\n toAddress,\n value,\n tokenContractAddress,\n expireTime,\n sequenceId\n )\n );\n\n verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);\n\n TransferHelper.safeTransfer(tokenContractAddress, toAddress, value);\n }\n\n /**\n * Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer\n *\n * @param forwarderAddress the address of the forwarder address to flush the tokens from\n * @param tokenContractAddress the address of the erc20 token contract\n */\n function flushForwarderTokens(\n address payable forwarderAddress,\n address tokenContractAddress\n ) external onlySigner {\n Forwarder forwarder = Forwarder(forwarderAddress);\n forwarder.flushTokens(tokenContractAddress);\n }\n\n /**\n * Do common multisig verification for both eth sends and erc20token transfers\n *\n * @param toAddress the destination address to send an outgoing transaction\n * @param operationHash see Data Formats\n * @param signature see Data Formats\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\n * returns address that has created the signature\n */\n function verifyMultiSig(\n address toAddress,\n bytes32 operationHash,\n bytes calldata signature,\n uint256 expireTime,\n uint256 sequenceId\n ) private returns (address) {\n address otherSigner = recoverAddressFromSignature(operationHash, signature);\n\n // Verify if we are in safe mode. In safe mode, the wallet can only send to signers\n require(!safeMode || isSigner(toAddress), \u0027External transfer in safe mode\u0027);\n\n // Verify that the transaction has not expired\n require(expireTime \u003e= block.timestamp, \u0027Transaction expired\u0027);\n\n // Try to insert the sequence ID. Will revert if the sequence id was invalid\n tryInsertSequenceId(sequenceId);\n\n require(isSigner(otherSigner), \u0027Invalid signer\u0027);\n\n require(otherSigner != msg.sender, \u0027Signers cannot be equal\u0027);\n\n return otherSigner;\n }\n\n /**\n * Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.\n */\n function activateSafeMode() external onlySigner {\n safeMode = true;\n SafeModeActivated(msg.sender);\n }\n\n /**\n * Gets signer\u0027s address using ecrecover\n * @param operationHash see Data Formats\n * @param signature see Data Formats\n * returns address recovered from the signature\n */\n function recoverAddressFromSignature(\n bytes32 operationHash,\n bytes memory signature\n ) private pure returns (address) {\n require(signature.length == 65, \u0027Invalid signature - wrong length\u0027);\n\n // We need to unpack the signature, which is given as an array of 65 bytes (like eth.sign)\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // solhint-disable-next-line\n assembly {\n r := mload(add(signature, 32))\n s := mload(add(signature, 64))\n v := and(mload(add(signature, 65)), 255)\n }\n if (v \u003c 27) {\n v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs\n }\n\n // protect against signature malleability\n // S value must be in the lower half orader\n // reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/051d340171a93a3d401aaaea46b4b62fa81e5d7c/contracts/cryptography/ECDSA.sol#L53\n require(\n uint256(s) \u003c=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,\n \"ECDSA: invalid signature \u0027s\u0027 value\"\n );\n\n // note that this returns 0 if the signature is invalid\n // Since 0x0 can never be a signer, when the recovered signer address\n // is checked against our signer list, that 0x0 will cause an invalid signer failure\n return ecrecover(operationHash, v, r, s);\n }\n\n /**\n * Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.\n * We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and\n * greater than the minimum element in the window.\n * @param sequenceId to insert into array of stored ids\n */\n function tryInsertSequenceId(uint256 sequenceId) private onlySigner {\n // Keep a pointer to the lowest value element in the window\n uint256 lowestValueIndex = 0;\n // fetch recentSequenceIds into memory for function context to avoid unnecessary sloads\n uint256[SEQUENCE_ID_WINDOW_SIZE] memory _recentSequenceIds = recentSequenceIds;\n for (uint256 i = 0; i \u003c SEQUENCE_ID_WINDOW_SIZE; i++) {\n require(_recentSequenceIds[i] != sequenceId, \u0027Sequence ID already used\u0027);\n\n if (_recentSequenceIds[i] \u003c _recentSequenceIds[lowestValueIndex]) {\n lowestValueIndex = i;\n }\n }\n\n // The sequence ID being used is lower than the lowest value in the window\n // so we cannot accept it as it may have been used before\n require(\n sequenceId \u003e _recentSequenceIds[lowestValueIndex],\n \u0027Sequence ID below window\u0027\n );\n\n // Block sequence IDs which are much higher than the lowest value\n // This prevents people blocking the contract by using very large sequence IDs quickly\n require(\n sequenceId \u003c=\n (_recentSequenceIds[lowestValueIndex] + MAX_SEQUENCE_ID_INCREASE),\n \u0027Sequence ID above maximum\u0027\n );\n\n recentSequenceIds[lowestValueIndex] = sequenceId;\n }\n\n /**\n * Gets the next available sequence ID for signing when using executeAndConfirm\n * returns the sequenceId one higher than the highest currently stored\n */\n function getNextSequenceId() public view returns (uint256) {\n uint256 highestSequenceId = 0;\n for (uint256 i = 0; i \u003c SEQUENCE_ID_WINDOW_SIZE; i++) {\n if (recentSequenceIds[i] \u003e highestSequenceId) {\n highestSequenceId = recentSequenceIds[i];\n }\n }\n return highestSequenceId + 1;\n }\n}\n"}}
|
1 | 19,499,932 |
e2b3b9df4a0af65d9016b6af83465ee4d300255ca8d83c230be25f11848f6dd1
|
c5a686689ad860f9d6967f2bd6245f1a6437f6f6c80e40a65d1ad2a60b54f436
|
b303bcc11cf1cb24f0742388a625bdfebf4a7296
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
72f84192cfc0020ddd037b01b6879825ab018b7c
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,499,934 |
fcdc83dc33c2236071a9e5734793e0a117d81971f0a8085b71a62d2615f217ff
|
1b09ff2663dafc20cd777ddf41d58169942ba5df3acc65bb565b07e41d9f52a8
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
efc99649e3a7058ed09a0e051baf0b49212733e4
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,499,934 |
fcdc83dc33c2236071a9e5734793e0a117d81971f0a8085b71a62d2615f217ff
|
ef250a68aef05287390040cd3bad0b6119a36daa77a3c3c4d17d4b778dae8576
|
b1a6bf349c947a540a5fe6f1e89992acdad836ab
|
e7d8df8f6546965a59dab007e8709965efe1255d
|
9ed551d69026643bf19df66b0db1dd13bfff8272
|
608060405234801561001057600080fd5b506040516101a23803806101a28339818101604052602081101561003357600080fd5b50516001600160a01b03811661007a5760405162461bcd60e51b815260040180806020018281038252602481526020018061017e6024913960400191505060405180910390fd5b600080546001600160a01b039092166001600160a01b031990921691909117905560d5806100a96000396000f3fe608060405236603757604051339034907f8863e458255c600ae3e61be347822f3ee57088c8538b68b5dd2357e682e59e1990600090a3005b600073ffffffffffffffffffffffffffffffffffffffff8154167fa619486e0000000000000000000000000000000000000000000000000000000082351415608157808252602082f35b3682833781823684845af490503d82833e80609a573d82fd5b503d81f3fea2646970667358221220c8ef5c5147809cc480e3260788e027fa751bfcf051cf3d463bbaeeff798437f364736f6c63430007060033496e76616c6964206d617374657220636f707920616464726573732070726f766964656400000000000000000000000023a19a97a2da581e3d66ef5fd1eea15024f55611
|
608060405236603757604051339034907f8863e458255c600ae3e61be347822f3ee57088c8538b68b5dd2357e682e59e1990600090a3005b600073ffffffffffffffffffffffffffffffffffffffff8154167fa619486e0000000000000000000000000000000000000000000000000000000082351415608157808252602082f35b3682833781823684845af490503d82833e80609a573d82fd5b503d81f3fea2646970667358221220c8ef5c5147809cc480e3260788e027fa751bfcf051cf3d463bbaeeff798437f364736f6c63430007060033
| |
1 | 19,499,935 |
a10d389b66f49bbfc8ee35e0ce60e2e4877a6ca413f166eddcaf7950767f6ad6
|
0ebe7d0e94f06a0a4d564ceb8154916e8f938ee8ae5502045e0dd95faa7351ce
|
db76311bb46e06833d534930e9e4539a0a134fa7
|
db76311bb46e06833d534930e9e4539a0a134fa7
|
fcdd01feeebe0a917a55ce66fca5ca1e8ee270fd
|
608060405234801561001057600080fd5b506040516109383803806109388339818101604052604081101561003357600080fd5b810190808051604051939291908464010000000082111561005357600080fd5b8382019150602082018581111561006957600080fd5b825186600182028301116401000000008211171561008657600080fd5b8083526020830192505050908051906020019080838360005b838110156100ba57808201518184015260208101905061009f565b50505050905090810190601f1680156100e75780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561010a57600080fd5b8382019150602082018581111561012057600080fd5b825186600182028301116401000000008211171561013d57600080fd5b8083526020830192505050908051906020019080838360005b83811015610171578082015181840152602081019050610156565b50505050905090810190601f16801561019e5780820380516001836020036101000a031916815260200191505b5060405250505081600090805190602001906101bb929190610243565b5080600190805190602001906101d2929190610243565b506040516101df906102c3565b604051809103906000f0801580156101fb573d6000803e3d6000fd5b50600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050506102f4565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061028457805160ff19168380011785556102b2565b828001600101855582156102b2579182015b828111156102b1578251825591602001919060010190610296565b5b5090506102bf91906102cf565b5090565b60fa8061083e83390190565b6102f191905b808211156102ed5760008160009055506001016102d5565b5090565b90565b61053b806103036000396000f3fe60806040526004361061004e5760003560e01c80631b55ba3a1461005a5780634fe6f55f1461006457806370e44c6a146100f45780638da5cb5b146100fe578063bedf0f4a1461018e57610055565b3661005557005b600080fd5b610062610198565b005b34801561007057600080fd5b506100796103c5565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b957808201518184015260208101905061009e565b50505050905090810190601f1680156100e65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100fc610463565b005b34801561010a57600080fd5b50610113610465565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610153578082015181840152602081019050610138565b50505050905090810190601f1680156101805780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610196610503565b005b600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663feae9ad36040518163ffffffff1660e01b815260040160206040518083038186803b15801561027057600080fd5b505afa158015610284573d6000803e3d6000fd5b505050506040513d602081101561029a57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f193505050501580156102f0573d6000803e3d6000fd5b50600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050565b60018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561045b5780601f106104305761010080835404028352916020019161045b565b820191906000526020600020905b81548152906001019060200180831161043e57829003601f168201915b505050505081565b565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104fb5780601f106104d0576101008083540402835291602001916104fb565b820191906000526020600020905b8154815290600101906020018083116104de57829003601f168201915b505050505081565b56fea26469706673582212200f005273c59eb01e2ac4044533bed1876e646bc1cc8d2dc69c1863046073b2c064736f6c63430006060033608060405234801561001057600080fd5b5060db8061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c0f93a1146037578063feae9ad314603f575b600080fd5b603d6087565b005b60456089565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b565b6000732c70a269380fac2bc22a218aaf822ebe603fb5c990509056fea264697066735822122023613d1a49b08f1719aa0b76eff883719f201eef2591468fbe4ca1ae4e96466364736f6c63430006060033000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002a30784442373633313142623436653036383333643533343933306539653435333961306131333446613700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002a30786441433137463935384432656535323361323230363230363939343539374331334438333165633700000000000000000000000000000000000000000000
|
60806040526004361061004e5760003560e01c80631b55ba3a1461005a5780634fe6f55f1461006457806370e44c6a146100f45780638da5cb5b146100fe578063bedf0f4a1461018e57610055565b3661005557005b600080fd5b610062610198565b005b34801561007057600080fd5b506100796103c5565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100b957808201518184015260208101905061009e565b50505050905090810190601f1680156100e65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100fc610463565b005b34801561010a57600080fd5b50610113610465565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610153578082015181840152602081019050610138565b50505050905090810190601f1680156101805780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610196610503565b005b600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663feae9ad36040518163ffffffff1660e01b815260040160206040518083038186803b15801561027057600080fd5b505afa158015610284573d6000803e3d6000fd5b505050506040513d602081101561029a57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f193505050501580156102f0573d6000803e3d6000fd5b50600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050600360009054906101000a905050565b60018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561045b5780601f106104305761010080835404028352916020019161045b565b820191906000526020600020905b81548152906001019060200180831161043e57829003601f168201915b505050505081565b565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104fb5780601f106104d0576101008083540402835291602001916104fb565b820191906000526020600020905b8154815290600101906020018083116104de57829003601f168201915b505050505081565b56fea26469706673582212200f005273c59eb01e2ac4044533bed1876e646bc1cc8d2dc69c1863046073b2c064736f6c63430006060033
| |
1 | 19,499,935 |
a10d389b66f49bbfc8ee35e0ce60e2e4877a6ca413f166eddcaf7950767f6ad6
|
0ebe7d0e94f06a0a4d564ceb8154916e8f938ee8ae5502045e0dd95faa7351ce
|
db76311bb46e06833d534930e9e4539a0a134fa7
|
fcdd01feeebe0a917a55ce66fca5ca1e8ee270fd
|
6f0a384ac43d1211c08fa48af780117cdc5e07f4
|
608060405234801561001057600080fd5b5060db8061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c0f93a1146037578063feae9ad314603f575b600080fd5b603d6087565b005b60456089565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b565b6000732c70a269380fac2bc22a218aaf822ebe603fb5c990509056fea264697066735822122023613d1a49b08f1719aa0b76eff883719f201eef2591468fbe4ca1ae4e96466364736f6c63430006060033
|
6080604052348015600f57600080fd5b506004361060325760003560e01c80630c0f93a1146037578063feae9ad314603f575b600080fd5b603d6087565b005b60456089565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b565b6000732c70a269380fac2bc22a218aaf822ebe603fb5c990509056fea264697066735822122023613d1a49b08f1719aa0b76eff883719f201eef2591468fbe4ca1ae4e96466364736f6c63430006060033
| |
1 | 19,499,935 |
a10d389b66f49bbfc8ee35e0ce60e2e4877a6ca413f166eddcaf7950767f6ad6
|
952f9519e3eeab9876089fb9bb99ae0167bf858ca259c898167fab950a2df133
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
310d351cbe32596a81b540e3c0893fa4af50b96d
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,499,937 |
4edf133f43c48650cafcf855cd79f567fa1ee77496a4114371e8fc54608a5667
|
b8aa61365044cc8409545d07725567c394e5a9d465ac7503db0554b91e6a06c1
|
3876070fc326adcaae96849df43674a4bda87efb
|
5c5708c6f9aaa28ddb9ec5bed1c972a612be5a90
|
fdd700afc9cab068e4adf74a3f2917efd26567bd
|
3d602d80600a3d3981f3363d3d373d3d3d363d73f35f82081c9f00f956c2d921e8157e0bb8936e255af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73f35f82081c9f00f956c2d921e8157e0bb8936e255af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,941 |
65baad1a5edb883e598573475439871d0fd0d4a21e06ddc2d2355eab43010bc5
|
315b161ca881d99e247d464611f01a914724a75aa3b33a38dc146ff831915346
|
d8e734fa9d779d242b0b905f8b2416f1491233ad
|
1f98431c8ad98523631ae4a59f267346ea31f984
|
a57ef40a7b9ea04c1d571605d968b6d7ec7bfbc0
|
6101606040523480156200001257600080fd5b503060601b60805260408051630890357360e41b81529051600091339163890357309160048082019260a092909190829003018186803b1580156200005657600080fd5b505afa1580156200006b573d6000803e3d6000fd5b505050506040513d60a08110156200008257600080fd5b508051602080830151604084015160608086015160809096015160e896871b6001600160e81b0319166101005291811b6001600160601b031990811660e05292811b831660c0529390931b1660a052600282810b900b90921b610120529150620000f79082906200010f811b62002b8417901c565b60801b6001600160801b03191661014052506200017d565b60008082600281900b620d89e719816200012557fe5b05029050600083600281900b620d89e8816200013d57fe5b0502905060008460020b83830360020b816200015557fe5b0560010190508062ffffff166001600160801b038016816200017357fe5b0495945050505050565b60805160601c60a05160601c60c05160601c60e05160601c6101005160e81c6101205160e81c6101405160801c61567e6200024a60003980611fee5280614b5f5280614b96525080610c0052806128fd5280614bca5280614bfc525080610cef52806119cb5280611a0252806129455250806111c75280611a855280611ef4528061244452806129215280613e6b5250806108d252806112f55280611a545280611e8e52806123be5280613d2252508061207b528061227d52806128d9525080612bfb525061567e6000f3fe608060405234801561001057600080fd5b50600436106101ae5760003560e01c806370cf754a116100ee578063c45a015511610097578063ddca3f4311610071578063ddca3f4314610800578063f305839914610820578063f30dba9314610828578063f637731d146108aa576101ae565b8063c45a0155146107d1578063d0c93a7c146107d9578063d21220a7146107f8576101ae565b8063883bdbfd116100c8578063883bdbfd14610633578063a34123a71461073c578063a38807f214610776576101ae565b806370cf754a146105c65780638206a4d1146105ce57806385b66729146105f6576101ae565b80633850c7bd1161015b578063490e6cbc11610135578063490e6cbc146104705780634f1eb3d8146104fc578063514ea4bf1461054d5780635339c296146105a6576101ae565b80633850c7bd1461035b5780633c8a7d8d146103b45780634614131914610456576101ae565b80631ad8b03b1161018c5780631ad8b03b146102aa578063252c09d7146102e157806332148f6714610338576101ae565b80630dfe1681146101b3578063128acb08146101d75780631a68650214610286575b600080fd5b6101bb6108d0565b604080516001600160a01b039092168252519081900360200190f35b61026d600480360360a08110156101ed57600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a08101608082013564010000000081111561022e57600080fd5b82018360208201111561024057600080fd5b8035906020019184600183028401116401000000008311171561026257600080fd5b5090925090506108f4565b6040805192835260208301919091528051918290030190f35b61028e6114ad565b604080516001600160801b039092168252519081900360200190f35b6102b26114bc565b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102fe600480360360208110156102f757600080fd5b50356114d6565b6040805163ffffffff909516855260069390930b60208501526001600160a01b039091168383015215156060830152519081900360800190f35b6103596004803603602081101561034e57600080fd5b503561ffff1661151c565b005b610363611616565b604080516001600160a01b03909816885260029690960b602088015261ffff9485168787015292841660608701529216608085015260ff90911660a0840152151560c0830152519081900360e00190f35b61026d600480360360a08110156103ca57600080fd5b6001600160a01b03823516916020810135600290810b92604083013590910b916001600160801b036060820135169181019060a08101608082013564010000000081111561041757600080fd5b82018360208201111561042957600080fd5b8035906020019184600183028401116401000000008311171561044b57600080fd5b509092509050611666565b61045e611922565b60408051918252519081900360200190f35b6103596004803603608081101561048657600080fd5b6001600160a01b0382351691602081013591604082013591908101906080810160608201356401000000008111156104bd57600080fd5b8201836020820111156104cf57600080fd5b803590602001918460018302840111640100000000831117156104f157600080fd5b509092509050611928565b6102b2600480360360a081101561051257600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b0360608201358116916080013516611d83565b61056a6004803603602081101561056357600080fd5b5035611f9d565b604080516001600160801b0396871681526020810195909552848101939093529084166060840152909216608082015290519081900360a00190f35b61045e600480360360208110156105bc57600080fd5b503560010b611fda565b61028e611fec565b610359600480360360408110156105e457600080fd5b5060ff81358116916020013516612010565b6102b26004803603606081101561060c57600080fd5b506001600160a01b03813516906001600160801b036020820135811691604001351661220f565b6106a36004803603602081101561064957600080fd5b81019060208101813564010000000081111561066457600080fd5b82018360208201111561067657600080fd5b8035906020019184602083028401116401000000008311171561069857600080fd5b5090925090506124dc565b604051808060200180602001838103835285818151815260200191508051906020019060200280838360005b838110156106e75781810151838201526020016106cf565b50505050905001838103825284818151815260200191508051906020019060200280838360005b8381101561072657818101518382015260200161070e565b5050505090500194505050505060405180910390f35b61026d6004803603606081101561075257600080fd5b508035600290810b91602081013590910b90604001356001600160801b0316612569565b6107a06004803603604081101561078c57600080fd5b508035600290810b9160200135900b6126e0565b6040805160069490940b84526001600160a01b03909216602084015263ffffffff1682820152519081900360600190f35b6101bb6128d7565b6107e16128fb565b6040805160029290920b8252519081900360200190f35b6101bb61291f565b610808612943565b6040805162ffffff9092168252519081900360200190f35b61045e612967565b6108486004803603602081101561083e57600080fd5b503560020b61296d565b604080516001600160801b039099168952600f9790970b602089015287870195909552606087019390935260069190910b60808601526001600160a01b031660a085015263ffffffff1660c0840152151560e083015251908190036101000190f35b610359600480360360208110156108c057600080fd5b50356001600160a01b03166129db565b7f000000000000000000000000000000000000000000000000000000000000000081565b6000806108ff612bf0565b85610936576040805162461bcd60e51b8152602060048201526002602482015261415360f01b604482015290519081900360640190fd5b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526109ef576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b87610a3a5780600001516001600160a01b0316866001600160a01b0316118015610a35575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038716105b610a6c565b80600001516001600160a01b0316866001600160a01b0316108015610a6c57506401000276a36001600160a01b038716115b610aa3576040805162461bcd60e51b815260206004820152600360248201526214d41360ea1b604482015290519081900360640190fd5b6000805460ff60f01b191681556040805160c08101909152808a610ad25760048460a0015160ff16901c610ae5565b60108460a0015160ff1681610ae357fe5b065b60ff1681526004546001600160801b03166020820152604001610b06612c27565b63ffffffff168152602001600060060b815260200160006001600160a01b031681526020016000151581525090506000808913905060006040518060e001604052808b81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018c610b8257600254610b86565b6001545b815260200160006001600160801b0316815260200184602001516001600160801b031681525090505b805115801590610bd55750886001600160a01b031681604001516001600160a01b031614155b15610f9f57610be261560e565b60408201516001600160a01b031681526060820151610c25906006907f00000000000000000000000000000000000000000000000000000000000000008f612c2b565b15156040830152600290810b810b60208301819052620d89e719910b1215610c5657620d89e7196020820152610c75565b6020810151620d89e860029190910b1315610c7557620d89e860208201525b610c828160200151612d6d565b6001600160a01b031660608201526040820151610d13908d610cbc578b6001600160a01b031683606001516001600160a01b031611610cd6565b8b6001600160a01b031683606001516001600160a01b0316105b610ce4578260600151610ce6565b8b5b60c085015185517f000000000000000000000000000000000000000000000000000000000000000061309f565b60c085015260a084015260808301526001600160a01b031660408301528215610d7557610d498160c00151826080015101613291565b825103825260a0810151610d6b90610d6090613291565b6020840151906132a7565b6020830152610db0565b610d828160a00151613291565b825101825260c08101516080820151610daa91610d9f9101613291565b6020840151906132c3565b60208301525b835160ff1615610df6576000846000015160ff168260c0015181610dd057fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610e3557610e298160c00151600160801b8460c001516001600160801b03166132d9565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610f5e57806040015115610f35578360a00151610ebf57610e9d846040015160008760200151886040015188602001518a606001516008613389909695949392919063ffffffff16565b6001600160a01b03166080860152600690810b900b6060850152600160a08501525b6000610f0b82602001518e610ed657600154610edc565b84608001515b8f610eeb578560800151610eef565b6002545b608089015160608a015160408b0151600595949392919061351c565b90508c15610f17576000035b610f258360c00151826135ef565b6001600160801b031660c0840152505b8b610f44578060200151610f4d565b60018160200151035b600290810b900b6060830152610f99565b80600001516001600160a01b031682604001516001600160a01b031614610f9957610f8c82604001516136a5565b600290810b900b60608301525b50610baf565b836020015160020b816060015160020b1461107a57600080610fed86604001518660400151886020015188602001518a606001518b6080015160086139d1909695949392919063ffffffff16565b604085015160608601516000805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b93909316929092029190911773ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03909116179055506110ac9050565b60408101516000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039092169190911790555b8060c001516001600160801b031683602001516001600160801b0316146110f25760c0810151600480546001600160801b0319166001600160801b039092169190911790555b8a1561114257608081015160015560a08101516001600160801b03161561113d5760a0810151600380546001600160801b031981166001600160801b03918216909301169190911790555b611188565b608081015160025560a08101516001600160801b0316156111885760a0810151600380546001600160801b03808216600160801b92839004821690940116029190911790555b8115158b1515146111a157602081015181518b036111ae565b80600001518a0381602001515b90965094508a156112e75760008512156111f0576111f07f00000000000000000000000000000000000000000000000000000000000000008d87600003613b86565b60006111fa613cd4565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b15801561127e57600080fd5b505af1158015611292573d6000803e3d6000fd5b5050505061129e613cd4565b6112a88289613e0d565b11156112e1576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b50611411565b600086121561131e5761131e7f00000000000000000000000000000000000000000000000000000000000000008d88600003613b86565b6000611328613e1d565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506113cc613e1d565b6113d68288613e0d565b111561140f576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b505b60408082015160c083015160608085015184518b8152602081018b90526001600160a01b03948516818701526001600160801b039093169183019190915260020b60808201529151908e169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679181900360a00190a350506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b6004546001600160801b031681565b6003546001600160801b0380821691600160801b90041682565b60088161ffff81106114e757600080fd5b015463ffffffff81169150640100000000810460060b90600160581b81046001600160a01b031690600160f81b900460ff1684565b600054600160f01b900460ff16611560576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611575612bf0565b60008054600160d81b900461ffff169061159160088385613eb5565b6000805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115fe576040805161ffff80851682528316602082015281517fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a929181900390910190a15b50506000805460ff60f01b1916600160f01b17905550565b6000546001600160a01b03811690600160a01b810460020b9061ffff600160b81b8204811691600160c81b8104821691600160d81b8204169060ff600160e81b8204811691600160f01b90041687565b600080548190600160f01b900460ff166116ad576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b191690556001600160801b0385166116cd57600080fd5b60008061171b60405180608001604052808c6001600160a01b031681526020018b60020b81526020018a60020b81526020016117118a6001600160801b0316613f58565b600f0b9052613f69565b9250925050819350809250600080600086111561173d5761173a613cd4565b91505b841561174e5761174b613e1d565b90505b336001600160a01b031663d348799787878b8b6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156117d057600080fd5b505af11580156117e4573d6000803e3d6000fd5b50505050600086111561183b576117f9613cd4565b6118038388613e0d565b111561183b576040805162461bcd60e51b815260206004820152600260248201526104d360f41b604482015290519081900360640190fd5b841561188b57611849613e1d565b6118538287613e0d565b111561188b576040805162461bcd60e51b81526020600482015260026024820152614d3160f01b604482015290519081900360640190fd5b8960020b8b60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8b8b60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a450506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b60025481565b600054600160f01b900460ff1661196c576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611981612bf0565b6004546001600160801b0316806119c3576040805162461bcd60e51b81526020600482015260016024820152601360fa1b604482015290519081900360640190fd5b60006119f8867f000000000000000000000000000000000000000000000000000000000000000062ffffff16620f42406141a9565b90506000611a2f867f000000000000000000000000000000000000000000000000000000000000000062ffffff16620f42406141a9565b90506000611a3b613cd4565b90506000611a47613e1d565b90508815611a7a57611a7a7f00000000000000000000000000000000000000000000000000000000000000008b8b613b86565b8715611aab57611aab7f00000000000000000000000000000000000000000000000000000000000000008b8a613b86565b336001600160a01b031663e9cbafb085858a8a6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b158015611b2d57600080fd5b505af1158015611b41573d6000803e3d6000fd5b505050506000611b4f613cd4565b90506000611b5b613e1d565b905081611b688588613e0d565b1115611ba0576040805162461bcd60e51b8152602060048201526002602482015261046360f41b604482015290519081900360640190fd5b80611bab8487613e0d565b1115611be3576040805162461bcd60e51b8152602060048201526002602482015261463160f01b604482015290519081900360640190fd5b8382038382038115611c725760008054600160e81b9004600f16908115611c16578160ff168481611c1057fe5b04611c19565b60005b90506001600160801b03811615611c4c57600380546001600160801b038082168401166001600160801b03199091161790555b611c66818503600160801b8d6001600160801b03166132d9565b60018054909101905550505b8015611cfd5760008054600160e81b900460041c600f16908115611ca2578160ff168381611c9c57fe5b04611ca5565b60005b90506001600160801b03811615611cd757600380546001600160801b03600160801b8083048216850182160291161790555b611cf1818403600160801b8d6001600160801b03166132d9565b60028054909101905550505b8d6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338f8f86866040518085815260200184815260200183815260200182815260200194505050505060405180910390a350506000805460ff60f01b1916600160f01b179055505050505050505050505050565b600080548190600160f01b900460ff16611dca576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19168155611de460073389896141e3565b60038101549091506001600160801b0390811690861611611e055784611e14565b60038101546001600160801b03165b60038201549093506001600160801b03600160801b909104811690851611611e3c5783611e52565b6003810154600160801b90046001600160801b03165b91506001600160801b03831615611eb7576003810180546001600160801b031981166001600160801b03918216869003821617909155611eb7907f0000000000000000000000000000000000000000000000000000000000000000908a908616613b86565b6001600160801b03821615611f1d576003810180546001600160801b03600160801b808304821686900382160291811691909117909155611f1d907f0000000000000000000000000000000000000000000000000000000000000000908a908516613b86565b604080516001600160a01b038a1681526001600160801b0380861660208301528416818301529051600288810b92908a900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a4506000805460ff60f01b1916600160f01b17905590969095509350505050565b60076020526000908152604090208054600182015460028301546003909301546001600160801b0392831693919281811691600160801b90041685565b60066020526000908152604090205481565b7f000000000000000000000000000000000000000000000000000000000000000081565b600054600160f01b900460ff16612054576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691638da5cb5b916004808301926020929190829003018186803b1580156120c157600080fd5b505afa1580156120d5573d6000803e3d6000fd5b505050506040513d60208110156120eb57600080fd5b50516001600160a01b0316331461210157600080fd5b60ff82161580612124575060048260ff16101580156121245750600a8260ff1611155b801561214e575060ff8116158061214e575060048160ff161015801561214e5750600a8160ff1611155b61215757600080fd5b60008054610ff0600484901b16840160ff908116600160e81b9081027fffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff841617909355919004167f973d8d92bb299f4af6ce49b52a8adb85ae46b9f214c4c4fc06ac77401237b1336010826040805160ff9390920683168252600f600486901c16602083015286831682820152918516606082015290519081900360800190a150506000805460ff60f01b1916600160f01b17905550565b600080548190600160f01b900460ff16612256576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691638da5cb5b916004808301926020929190829003018186803b1580156122c357600080fd5b505afa1580156122d7573d6000803e3d6000fd5b505050506040513d60208110156122ed57600080fd5b50516001600160a01b0316331461230357600080fd5b6003546001600160801b039081169085161161231f578361232c565b6003546001600160801b03165b6003549092506001600160801b03600160801b9091048116908416116123525782612366565b600354600160801b90046001600160801b03165b90506001600160801b038216156123e7576003546001600160801b038381169116141561239557600019909101905b600380546001600160801b031981166001600160801b039182168590038216179091556123e7907f00000000000000000000000000000000000000000000000000000000000000009087908516613b86565b6001600160801b0381161561246d576003546001600160801b03828116600160801b90920416141561241857600019015b600380546001600160801b03600160801b80830482168590038216029181169190911790915561246d907f00000000000000000000000000000000000000000000000000000000000000009087908416613b86565b604080516001600160801b0380851682528316602082015281516001600160a01b0388169233927f596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151929081900390910190a36000805460ff60f01b1916600160f01b1790559094909350915050565b6060806124e7612bf0565b61255e6124f2612c27565b858580806020026020016040519081016040528093929190818152602001838360200280828437600092018290525054600454600896959450600160a01b820460020b935061ffff600160b81b8304811693506001600160801b0390911691600160c81b900416614247565b915091509250929050565b600080548190600160f01b900460ff166125b0576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916815560408051608081018252338152600288810b602083015287900b918101919091528190819061260990606081016125fc6001600160801b038a16613f58565b600003600f0b9052613f69565b925092509250816000039450806000039350600085118061262a5750600084115b15612669576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b604080516001600160801b0388168152602081018790528082018690529051600289810b92908b900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a450506000805460ff60f01b1916600160f01b179055509094909350915050565b60008060006126ed612bf0565b6126f785856143a1565b600285810b810b60009081526005602052604080822087840b90930b825281206003830154600681900b9367010000000000000082046001600160a01b0316928492600160d81b810463ffffffff169284929091600160f81b900460ff168061275f57600080fd5b6003820154600681900b985067010000000000000081046001600160a01b03169650600160d81b810463ffffffff169450600160f81b900460ff16806127a457600080fd5b50506040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b810b6020840181905261ffff600160b81b8404811695850195909552600160c81b830485166060850152600160d81b8304909416608084015260ff600160e81b8304811660a0850152600160f01b909204909116151560c08301529093508e810b91900b1215905061284d575093909403965090039350900390506128d0565b8a60020b816020015160020b12156128c1576000612869612c27565b602083015160408401516004546060860151939450600093849361289f936008938893879392916001600160801b031690613389565b9a9003989098039b5050949096039290920396509091030392506128d0915050565b50949093039650039350900390505b9250925092565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b60015481565b60056020526000908152604090208054600182015460028301546003909301546001600160801b03831693600160801b909304600f0b9290600681900b9067010000000000000081046001600160a01b031690600160d81b810463ffffffff1690600160f81b900460ff1688565b6000546001600160a01b031615612a1e576040805162461bcd60e51b8152602060048201526002602482015261414960f01b604482015290519081900360640190fd5b6000612a29826136a5565b9050600080612a41612a39612c27565b60089061446a565b6040805160e0810182526001600160a01b038816808252600288810b6020808501829052600085870181905261ffff898116606088018190529089166080880181905260a08801839052600160c0909801979097528154600160f01b73ffffffffffffffffffffffffffffffffffffffff19909116871762ffffff60a01b1916600160a01b62ffffff9787900b9790971696909602959095177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9091021761ffff60d81b1916600160d81b909602959095177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1692909217909355835191825281019190915281519395509193507f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9592918290030190a150505050565b60008082600281900b620d89e71981612b9957fe5b05029050600083600281900b620d89e881612bb057fe5b0502905060008460020b83830360020b81612bc757fe5b0560010190508062ffffff166001600160801b03801681612be457fe5b0493505050505b919050565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612c2557600080fd5b565b4290565b60008060008460020b8660020b81612c3f57fe5b05905060008660020b128015612c6657508460020b8660020b81612c5f57fe5b0760020b15155b15612c7057600019015b8315612ce557600080612c82836144b6565b600182810b810b600090815260208d9052604090205460ff83169190911b80016000190190811680151597509294509092509085612cc757888360ff16860302612cda565b88612cd1826144c8565b840360ff168603025b965050505050612d63565b600080612cf4836001016144b6565b91509150600060018260ff166001901b031990506000818b60008660010b60010b8152602001908152602001600020541690508060001415955085612d4657888360ff0360ff16866001010102612d5c565b8883612d5183614568565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b12612d84578260020b612d8c565b8260020b6000035b9050620d89e8811115612dca576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612dde57600160801b612df0565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e24576ffff97272373d413259a46990580e213a0260801c5b6004821615612e43576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e62576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e81576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612ea0576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612ebf576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ede576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612efe576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f1e576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f3e576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f5e576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f7e576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f9e576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612fbe576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fde576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612fff576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561301f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561303e576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561305b576b048a170391f7dc42444e8fa20260801c5b60008460020b131561307657806000198161307257fe5b0490505b64010000000081061561308a57600161308d565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906131245760006130d88989620f42400362ffffff16620f42406132d9565b9050826130f1576130ec8c8c8c6001614652565b6130fe565b6130fe8b8d8c60016146cd565b955085811061310f578a965061311e565b61311b8c8b838661478a565b96505b5061316e565b8161313b576131368b8b8b60006146cd565b613148565b6131488a8c8b6000614652565b935083886000031061315c5789955061316e565b61316b8b8a8a600003856147d6565b95505b6001600160a01b038a81169087161482156131d15780801561318d5750815b6131a35761319e878d8c60016146cd565b6131a5565b855b95508080156131b2575081155b6131c8576131c3878d8c6000614652565b6131ca565b845b945061321b565b8080156131db5750815b6131f1576131ec8c888c6001614652565b6131f3565b855b9550808015613200575081155b613216576132118c888c60006146cd565b613218565b845b94505b8115801561322b57508860000385115b15613237578860000394505b81801561325657508a6001600160a01b0316876001600160a01b031614155b15613265578589039350613282565b61327f868962ffffff168a620f42400362ffffff166141a9565b93505b50505095509550955095915050565b6000600160ff1b82106132a357600080fd5b5090565b808203828113156000831215146132bd57600080fd5b92915050565b818101828112156000831215146132bd57600080fd5b600080806000198587098686029250828110908390030390508061330f576000841161330457600080fd5b508290049050613382565b80841161331b57600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008063ffffffff8716613430576000898661ffff1661ffff81106133aa57fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a161461341c57613419818a8988614822565b90505b806020015181604001519250925050613510565b8688036000806134458c8c858c8c8c8c6148d2565b91509150816000015163ffffffff168363ffffffff161415613477578160200151826040015194509450505050613510565b805163ffffffff8481169116141561349f578060200151816040015194509450505050613510565b8151815160208085015190840151918390039286039163ffffffff80841692908516910360060b816134cd57fe5b05028460200151018263ffffffff168263ffffffff1686604001518660400151036001600160a01b031602816134ff57fe5b048560400151019650965050505050505b97509795505050505050565b600295860b860b60009081526020979097526040909620600181018054909503909455938301805490920390915560038201805463ffffffff600160d81b6001600160a01b036701000000000000008085048216909603169094027fffffffffff0000000000000000000000000000000000000000ffffffffffffff90921691909117600681810b90960390950b66ffffffffffffff1666ffffffffffffff199095169490941782810485169095039093160263ffffffff60d81b1990931692909217905554600160801b9004600f0b90565b60008082600f0b121561365457826001600160801b03168260000384039150816001600160801b03161061364f576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b6132bd565b826001600160801b03168284019150816001600160801b031610156132bd576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b038316108015906136e1575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613716576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106137b757607f810383901c91506137c1565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146139c257886001600160a01b03166139a682612d6d565b6001600160a01b031611156139bb57816139bd565b805b6139c4565b815b9998505050505050505050565b6000806000898961ffff1661ffff81106139e757fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff161515606083015290925089161415613a575788859250925050613510565b8461ffff168461ffff16118015613a7857506001850361ffff168961ffff16145b15613a8557839150613a89565b8491505b8161ffff168960010161ffff1681613a9d57fe5b069250613aac81898989614822565b8a8461ffff1661ffff8110613abd57fe5b825191018054602084015160408501516060909501511515600160f81b027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b03909616600160581b027fff0000000000000000000000000000000000000000ffffffffffffffffffffff60069390930b66ffffffffffffff16640100000000026affffffffffffff000000001963ffffffff90971663ffffffff199095169490941795909516929092171692909217929092161790555097509795505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c025780518252601f199092019160209182019101613be3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c64576040519150601f19603f3d011682016040523d82523d6000602084013e613c69565b606091505b5091509150818015613c97575080511580613c975750808060200190516020811015613c9457600080fd5b50515b613ccd576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b5050505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001693919290918291908083835b60208310613d6d5780518252601f199092019160209182019101613d4e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613dcd576040519150601f19603f3d011682016040523d82523d6000602084013e613dd2565b606091505b5091509150818015613de657506020815110155b613def57600080fd5b808060200190516020811015613e0457600080fd5b50519250505090565b808201828110156132bd57600080fd5b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016939192909182919080838360208310613d6d5780518252601f199092019160209182019101613d4e565b6000808361ffff1611613ef3576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b8261ffff168261ffff1611613f09575081613382565b825b8261ffff168161ffff161015613f4f576001858261ffff1661ffff8110613f2e57fe5b01805463ffffffff191663ffffffff92909216919091179055600101613f0b565b50909392505050565b80600f81900b8114612beb57600080fd5b6000806000613f76612bf0565b613f88846020015185604001516143a1565b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602080840182905261ffff600160b81b8404811685870152600160c81b84048116606080870191909152600160d81b8504909116608086015260ff600160e81b8504811660a0870152600160f01b909404909316151560c08501528851908901519489015192890151939461402c9491939092909190614acf565b93508460600151600f0b6000146141a157846020015160020b816020015160020b12156140815761407a6140638660200151612d6d565b6140708760400151612d6d565b8760600151614c84565b92506141a1565b846040015160020b816020015160020b12156141775760045460408201516001600160801b03909116906140d3906140b7612c27565b60208501516060860151608087015160089493929187916139d1565b6000805461ffff60c81b1916600160c81b61ffff938416021761ffff60b81b1916600160b81b939092169290920217905581516040870151614123919061411990612d6d565b8860600151614c84565b93506141416141358760200151612d6d565b83516060890151614cc8565b92506141518187606001516135ef565b600480546001600160801b0319166001600160801b0392909216919091179055506141a1565b61419e6141878660200151612d6d565b6141948760400151612d6d565b8760600151614cc8565b91505b509193909250565b60006141b68484846132d9565b9050600082806141c257fe5b84860911156133825760001981106141d957600080fd5b6001019392505050565b6040805160609490941b6bffffffffffffffffffffffff1916602080860191909152600293840b60e890811b60348701529290930b90911b60378401528051808403601a018152603a90930181528251928201929092206000908152929052902090565b60608060008361ffff1611614287576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b865167ffffffffffffffff8111801561429f57600080fd5b506040519080825280602002602001820160405280156142c9578160200160208202803683370190505b509150865167ffffffffffffffff811180156142e457600080fd5b5060405190808252806020026020018201604052801561430e578160200160208202803683370190505b50905060005b87518110156143945761433f8a8a8a848151811061432e57fe5b60200260200101518a8a8a8a613389565b84838151811061434b57fe5b6020026020010184848151811061435e57fe5b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b81525050508080600101915050614314565b5097509795505050505050565b8060020b8260020b126143e1576040805162461bcd60e51b8152602060048201526003602482015262544c5560e81b604482015290519081900360640190fd5b620d89e719600283900b1215614424576040805162461bcd60e51b8152602060048201526003602482015262544c4d60e81b604482015290519081900360640190fd5b620d89e8600282900b1315614466576040805162461bcd60e51b815260206004820152600360248201526254554d60e81b604482015290519081900360640190fd5b5050565b6040805160808101825263ffffffff9283168082526000602083018190529282019290925260016060909101819052835463ffffffff1916909117909116600160f81b17909155908190565b60020b600881901d9161010090910790565b60008082116144d657600080fd5b600160801b82106144e957608091821c91015b68010000000000000000821061450157604091821c91015b640100000000821061451557602091821c91015b62010000821061452757601091821c91015b610100821061453857600891821c91015b6010821061454857600491821c91015b6004821061455857600291821c91015b60028210612beb57600101919050565b600080821161457657600080fd5b5060ff6001600160801b0382161561459157607f1901614599565b608082901c91505b67ffffffffffffffff8216156145b257603f19016145ba565b604082901c91505b63ffffffff8216156145cf57601f19016145d7565b602082901c91505b61ffff8216156145ea57600f19016145f2565b601082901c91505b60ff821615614604576007190161460c565b600882901c91505b600f82161561461e5760031901614626565b600482901c91505b60038216156146385760011901614640565b600282901c91505b6001821615612beb5760001901919050565b6000836001600160a01b0316856001600160a01b03161115614672579293925b8161469f5761469a836001600160801b03168686036001600160a01b0316600160601b6132d9565b6146c2565b6146c2836001600160801b03168686036001600160a01b0316600160601b6141a9565b90505b949350505050565b6000836001600160a01b0316856001600160a01b031611156146ed579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661472957600080fd5b8361475957866001600160a01b031661474c8383896001600160a01b03166132d9565b8161475357fe5b0461477f565b61477f6147708383896001600160a01b03166141a9565b886001600160a01b0316614cf7565b979650505050505050565b600080856001600160a01b0316116147a157600080fd5b6000846001600160801b0316116147b757600080fd5b816147c95761469a8585856001614d02565b6146c28585856001614de3565b600080856001600160a01b0316116147ed57600080fd5b6000846001600160801b03161161480357600080fd5b816148155761469a8585856000614de3565b6146c28585856000614d02565b61482a61564a565b600085600001518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020016000856001600160801b03161161487e576001614880565b845b6001600160801b031673ffffffff00000000000000000000000000000000608085901b16816148ab57fe5b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b6148da61564a565b6148e261564a565b888561ffff1661ffff81106148f357fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff1615156060820152925061495890899089614ed8565b15614990578663ffffffff16826000015163ffffffff16141561497a57613510565b8161498783898988614822565b91509150613510565b888361ffff168660010161ffff16816149a557fe5b0661ffff1661ffff81106149b557fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909250614a6c57604080516080810182528a5463ffffffff811682526401000000008104600690810b810b900b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b614a7b88836000015189614ed8565b614ab2576040805162461bcd60e51b815260206004820152600360248201526213d31160ea1b604482015290519081900360640190fd5b614abf8989898887614f9b565b9150915097509795505050505050565b6000614ade60078787876141e3565b60015460025491925090600080600f87900b15614c24576000614aff612c27565b6000805460045492935090918291614b499160089186918591600160a01b810460020b9161ffff600160b81b83048116926001600160801b0390921691600160c81b900416613389565b9092509050614b8360058d8b8d8b8b87898b60007f000000000000000000000000000000000000000000000000000000000000000061513b565b9450614bba60058c8b8d8b8b87898b60017f000000000000000000000000000000000000000000000000000000000000000061513b565b93508415614bee57614bee60068d7f0000000000000000000000000000000000000000000000000000000000000000615325565b8315614c2057614c2060068c7f0000000000000000000000000000000000000000000000000000000000000000615325565b5050505b600080614c3660058c8c8b8a8a61538b565b9092509050614c47878a8484615437565b600089600f0b1215614c75578315614c6457614c6460058c6155cc565b8215614c7557614c7560058b6155cc565b50505050505095945050505050565b60008082600f0b12614caa57614ca5614ca085858560016146cd565b613291565b6146c5565b614cbd614ca085858560000360006146cd565b600003949350505050565b60008082600f0b12614ce457614ca5614ca08585856001614652565b614cbd614ca08585856000036000614652565b808204910615150190565b60008115614d755760006001600160a01b03841115614d3857614d3384600160601b876001600160801b03166132d9565b614d50565b6001600160801b038516606085901b81614d4e57fe5b045b9050614d6d614d686001600160a01b03881683613e0d565b6155f8565b9150506146c5565b60006001600160a01b03841115614da357614d9e84600160601b876001600160801b03166141a9565b614dba565b614dba606085901b6001600160801b038716614cf7565b905080866001600160a01b031611614dd157600080fd5b6001600160a01b0386160390506146c5565b600082614df15750836146c5565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b168215614e91576001600160a01b03861684810290858281614e3157fe5b041415614e6257818101828110614e6057614e5683896001600160a01b0316836141a9565b93505050506146c5565b505b614e8882614e83878a6001600160a01b03168681614e7c57fe5b0490613e0d565b614cf7565b925050506146c5565b6001600160a01b03861684810290858281614ea857fe5b04148015614eb557508082115b614ebe57600080fd5b808203614e56614d68846001600160a01b038b16846141a9565b60008363ffffffff168363ffffffff1611158015614f0257508363ffffffff168263ffffffff1611155b15614f1e578163ffffffff168363ffffffff1611159050613382565b60008463ffffffff168463ffffffff1611614f46578363ffffffff1664010000000001614f4e565b8363ffffffff165b64ffffffffff16905060008563ffffffff168463ffffffff1611614f7f578363ffffffff1664010000000001614f87565b8363ffffffff165b64ffffffffff169091111595945050505050565b614fa361564a565b614fab61564a565b60008361ffff168560010161ffff1681614fc157fe5b0661ffff169050600060018561ffff16830103905060005b506002818301048961ffff87168281614fee57fe5b0661ffff8110614ffa57fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290955061506557806001019250614fd9565b898661ffff16826001018161507657fe5b0661ffff811061508257fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094506000906150ed908b908b614ed8565b905080801561510657506151068a8a8760000151614ed8565b15615111575061512e565b8061512157600182039250615128565b8160010193505b50614fd9565b5050509550959350505050565b60028a810b900b600090815260208c90526040812080546001600160801b031682615166828d6135ef565b9050846001600160801b0316816001600160801b031611156151b4576040805162461bcd60e51b81526020600482015260026024820152614c4f60f01b604482015290519081900360640190fd5b6001600160801b03828116159082161581141594501561528a578c60020b8e60020b1361525a57600183018b9055600283018a90556003830180547fffffffffff0000000000000000000000000000000000000000ffffffffffffff166701000000000000006001600160a01b038c16021766ffffffffffffff191666ffffffffffffff60068b900b161763ffffffff60d81b1916600160d81b63ffffffff8a16021790555b6003830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b038216178355856152d35782546152ce906152c990600160801b9004600f90810b810b908f900b6132c3565b613f58565b6152f4565b82546152f4906152c990600160801b9004600f90810b810b908f900b6132a7565b8354600f9190910b6001600160801b03908116600160801b0291161790925550909c9b505050505050505050505050565b8060020b8260020b8161533457fe5b0760020b1561534257600080fd5b60008061535d8360020b8560020b8161535757fe5b056144b6565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b126153d1575050600182015460028301546153e4565b8360010154880391508360020154870390505b6000808b60020b8b60020b121561540657505060018301546002840154615419565b84600101548a0391508460020154890390505b92909803979097039b96909503949094039850939650505050505050565b6040805160a08101825285546001600160801b0390811682526001870154602083015260028701549282019290925260038601548083166060830152600160801b900490911660808201526000600f85900b6154d65781516001600160801b03166154ce576040805162461bcd60e51b815260206004820152600260248201526104e560f41b604482015290519081900360640190fd5b5080516154e5565b81516154e290866135ef565b90505b60006155098360200151860384600001516001600160801b0316600160801b6132d9565b9050600061552f8460400151860385600001516001600160801b0316600160801b6132d9565b905086600f0b6000146155565787546001600160801b0319166001600160801b0384161788555b60018801869055600288018590556001600160801b03821615158061558457506000816001600160801b0316115b156155c2576003880180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b5050505050505050565b600290810b810b6000908152602092909252604082208281556001810183905590810182905560030155565b806001600160a01b0381168114612beb57600080fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160808101825260008082526020820181905291810182905260608101919091529056fea164736f6c6343000706000a
|
608060405234801561001057600080fd5b50600436106101ae5760003560e01c806370cf754a116100ee578063c45a015511610097578063ddca3f4311610071578063ddca3f4314610800578063f305839914610820578063f30dba9314610828578063f637731d146108aa576101ae565b8063c45a0155146107d1578063d0c93a7c146107d9578063d21220a7146107f8576101ae565b8063883bdbfd116100c8578063883bdbfd14610633578063a34123a71461073c578063a38807f214610776576101ae565b806370cf754a146105c65780638206a4d1146105ce57806385b66729146105f6576101ae565b80633850c7bd1161015b578063490e6cbc11610135578063490e6cbc146104705780634f1eb3d8146104fc578063514ea4bf1461054d5780635339c296146105a6576101ae565b80633850c7bd1461035b5780633c8a7d8d146103b45780634614131914610456576101ae565b80631ad8b03b1161018c5780631ad8b03b146102aa578063252c09d7146102e157806332148f6714610338576101ae565b80630dfe1681146101b3578063128acb08146101d75780631a68650214610286575b600080fd5b6101bb6108d0565b604080516001600160a01b039092168252519081900360200190f35b61026d600480360360a08110156101ed57600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a08101608082013564010000000081111561022e57600080fd5b82018360208201111561024057600080fd5b8035906020019184600183028401116401000000008311171561026257600080fd5b5090925090506108f4565b6040805192835260208301919091528051918290030190f35b61028e6114ad565b604080516001600160801b039092168252519081900360200190f35b6102b26114bc565b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102fe600480360360208110156102f757600080fd5b50356114d6565b6040805163ffffffff909516855260069390930b60208501526001600160a01b039091168383015215156060830152519081900360800190f35b6103596004803603602081101561034e57600080fd5b503561ffff1661151c565b005b610363611616565b604080516001600160a01b03909816885260029690960b602088015261ffff9485168787015292841660608701529216608085015260ff90911660a0840152151560c0830152519081900360e00190f35b61026d600480360360a08110156103ca57600080fd5b6001600160a01b03823516916020810135600290810b92604083013590910b916001600160801b036060820135169181019060a08101608082013564010000000081111561041757600080fd5b82018360208201111561042957600080fd5b8035906020019184600183028401116401000000008311171561044b57600080fd5b509092509050611666565b61045e611922565b60408051918252519081900360200190f35b6103596004803603608081101561048657600080fd5b6001600160a01b0382351691602081013591604082013591908101906080810160608201356401000000008111156104bd57600080fd5b8201836020820111156104cf57600080fd5b803590602001918460018302840111640100000000831117156104f157600080fd5b509092509050611928565b6102b2600480360360a081101561051257600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b0360608201358116916080013516611d83565b61056a6004803603602081101561056357600080fd5b5035611f9d565b604080516001600160801b0396871681526020810195909552848101939093529084166060840152909216608082015290519081900360a00190f35b61045e600480360360208110156105bc57600080fd5b503560010b611fda565b61028e611fec565b610359600480360360408110156105e457600080fd5b5060ff81358116916020013516612010565b6102b26004803603606081101561060c57600080fd5b506001600160a01b03813516906001600160801b036020820135811691604001351661220f565b6106a36004803603602081101561064957600080fd5b81019060208101813564010000000081111561066457600080fd5b82018360208201111561067657600080fd5b8035906020019184602083028401116401000000008311171561069857600080fd5b5090925090506124dc565b604051808060200180602001838103835285818151815260200191508051906020019060200280838360005b838110156106e75781810151838201526020016106cf565b50505050905001838103825284818151815260200191508051906020019060200280838360005b8381101561072657818101518382015260200161070e565b5050505090500194505050505060405180910390f35b61026d6004803603606081101561075257600080fd5b508035600290810b91602081013590910b90604001356001600160801b0316612569565b6107a06004803603604081101561078c57600080fd5b508035600290810b9160200135900b6126e0565b6040805160069490940b84526001600160a01b03909216602084015263ffffffff1682820152519081900360600190f35b6101bb6128d7565b6107e16128fb565b6040805160029290920b8252519081900360200190f35b6101bb61291f565b610808612943565b6040805162ffffff9092168252519081900360200190f35b61045e612967565b6108486004803603602081101561083e57600080fd5b503560020b61296d565b604080516001600160801b039099168952600f9790970b602089015287870195909552606087019390935260069190910b60808601526001600160a01b031660a085015263ffffffff1660c0840152151560e083015251908190036101000190f35b610359600480360360208110156108c057600080fd5b50356001600160a01b03166129db565b7f00000000000000000000000097d0cfeb4fde54b430307c9482d6f79c761fe9b681565b6000806108ff612bf0565b85610936576040805162461bcd60e51b8152602060048201526002602482015261415360f01b604482015290519081900360640190fd5b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526109ef576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b87610a3a5780600001516001600160a01b0316866001600160a01b0316118015610a35575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038716105b610a6c565b80600001516001600160a01b0316866001600160a01b0316108015610a6c57506401000276a36001600160a01b038716115b610aa3576040805162461bcd60e51b815260206004820152600360248201526214d41360ea1b604482015290519081900360640190fd5b6000805460ff60f01b191681556040805160c08101909152808a610ad25760048460a0015160ff16901c610ae5565b60108460a0015160ff1681610ae357fe5b065b60ff1681526004546001600160801b03166020820152604001610b06612c27565b63ffffffff168152602001600060060b815260200160006001600160a01b031681526020016000151581525090506000808913905060006040518060e001604052808b81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018c610b8257600254610b86565b6001545b815260200160006001600160801b0316815260200184602001516001600160801b031681525090505b805115801590610bd55750886001600160a01b031681604001516001600160a01b031614155b15610f9f57610be261560e565b60408201516001600160a01b031681526060820151610c25906006907f00000000000000000000000000000000000000000000000000000000000000c88f612c2b565b15156040830152600290810b810b60208301819052620d89e719910b1215610c5657620d89e7196020820152610c75565b6020810151620d89e860029190910b1315610c7557620d89e860208201525b610c828160200151612d6d565b6001600160a01b031660608201526040820151610d13908d610cbc578b6001600160a01b031683606001516001600160a01b031611610cd6565b8b6001600160a01b031683606001516001600160a01b0316105b610ce4578260600151610ce6565b8b5b60c085015185517f000000000000000000000000000000000000000000000000000000000000271061309f565b60c085015260a084015260808301526001600160a01b031660408301528215610d7557610d498160c00151826080015101613291565b825103825260a0810151610d6b90610d6090613291565b6020840151906132a7565b6020830152610db0565b610d828160a00151613291565b825101825260c08101516080820151610daa91610d9f9101613291565b6020840151906132c3565b60208301525b835160ff1615610df6576000846000015160ff168260c0015181610dd057fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610e3557610e298160c00151600160801b8460c001516001600160801b03166132d9565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610f5e57806040015115610f35578360a00151610ebf57610e9d846040015160008760200151886040015188602001518a606001516008613389909695949392919063ffffffff16565b6001600160a01b03166080860152600690810b900b6060850152600160a08501525b6000610f0b82602001518e610ed657600154610edc565b84608001515b8f610eeb578560800151610eef565b6002545b608089015160608a015160408b0151600595949392919061351c565b90508c15610f17576000035b610f258360c00151826135ef565b6001600160801b031660c0840152505b8b610f44578060200151610f4d565b60018160200151035b600290810b900b6060830152610f99565b80600001516001600160a01b031682604001516001600160a01b031614610f9957610f8c82604001516136a5565b600290810b900b60608301525b50610baf565b836020015160020b816060015160020b1461107a57600080610fed86604001518660400151886020015188602001518a606001518b6080015160086139d1909695949392919063ffffffff16565b604085015160608601516000805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b93909316929092029190911773ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03909116179055506110ac9050565b60408101516000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039092169190911790555b8060c001516001600160801b031683602001516001600160801b0316146110f25760c0810151600480546001600160801b0319166001600160801b039092169190911790555b8a1561114257608081015160015560a08101516001600160801b03161561113d5760a0810151600380546001600160801b031981166001600160801b03918216909301169190911790555b611188565b608081015160025560a08101516001600160801b0316156111885760a0810151600380546001600160801b03808216600160801b92839004821690940116029190911790555b8115158b1515146111a157602081015181518b036111ae565b80600001518a0381602001515b90965094508a156112e75760008512156111f0576111f07f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28d87600003613b86565b60006111fa613cd4565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b15801561127e57600080fd5b505af1158015611292573d6000803e3d6000fd5b5050505061129e613cd4565b6112a88289613e0d565b11156112e1576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b50611411565b600086121561131e5761131e7f00000000000000000000000097d0cfeb4fde54b430307c9482d6f79c761fe9b68d88600003613b86565b6000611328613e1d565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506113cc613e1d565b6113d68288613e0d565b111561140f576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b505b60408082015160c083015160608085015184518b8152602081018b90526001600160a01b03948516818701526001600160801b039093169183019190915260020b60808201529151908e169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679181900360a00190a350506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b6004546001600160801b031681565b6003546001600160801b0380821691600160801b90041682565b60088161ffff81106114e757600080fd5b015463ffffffff81169150640100000000810460060b90600160581b81046001600160a01b031690600160f81b900460ff1684565b600054600160f01b900460ff16611560576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611575612bf0565b60008054600160d81b900461ffff169061159160088385613eb5565b6000805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115fe576040805161ffff80851682528316602082015281517fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a929181900390910190a15b50506000805460ff60f01b1916600160f01b17905550565b6000546001600160a01b03811690600160a01b810460020b9061ffff600160b81b8204811691600160c81b8104821691600160d81b8204169060ff600160e81b8204811691600160f01b90041687565b600080548190600160f01b900460ff166116ad576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b191690556001600160801b0385166116cd57600080fd5b60008061171b60405180608001604052808c6001600160a01b031681526020018b60020b81526020018a60020b81526020016117118a6001600160801b0316613f58565b600f0b9052613f69565b9250925050819350809250600080600086111561173d5761173a613cd4565b91505b841561174e5761174b613e1d565b90505b336001600160a01b031663d348799787878b8b6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156117d057600080fd5b505af11580156117e4573d6000803e3d6000fd5b50505050600086111561183b576117f9613cd4565b6118038388613e0d565b111561183b576040805162461bcd60e51b815260206004820152600260248201526104d360f41b604482015290519081900360640190fd5b841561188b57611849613e1d565b6118538287613e0d565b111561188b576040805162461bcd60e51b81526020600482015260026024820152614d3160f01b604482015290519081900360640190fd5b8960020b8b60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8b8b60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a450506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b60025481565b600054600160f01b900460ff1661196c576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611981612bf0565b6004546001600160801b0316806119c3576040805162461bcd60e51b81526020600482015260016024820152601360fa1b604482015290519081900360640190fd5b60006119f8867f000000000000000000000000000000000000000000000000000000000000271062ffffff16620f42406141a9565b90506000611a2f867f000000000000000000000000000000000000000000000000000000000000271062ffffff16620f42406141a9565b90506000611a3b613cd4565b90506000611a47613e1d565b90508815611a7a57611a7a7f00000000000000000000000097d0cfeb4fde54b430307c9482d6f79c761fe9b68b8b613b86565b8715611aab57611aab7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28b8a613b86565b336001600160a01b031663e9cbafb085858a8a6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b158015611b2d57600080fd5b505af1158015611b41573d6000803e3d6000fd5b505050506000611b4f613cd4565b90506000611b5b613e1d565b905081611b688588613e0d565b1115611ba0576040805162461bcd60e51b8152602060048201526002602482015261046360f41b604482015290519081900360640190fd5b80611bab8487613e0d565b1115611be3576040805162461bcd60e51b8152602060048201526002602482015261463160f01b604482015290519081900360640190fd5b8382038382038115611c725760008054600160e81b9004600f16908115611c16578160ff168481611c1057fe5b04611c19565b60005b90506001600160801b03811615611c4c57600380546001600160801b038082168401166001600160801b03199091161790555b611c66818503600160801b8d6001600160801b03166132d9565b60018054909101905550505b8015611cfd5760008054600160e81b900460041c600f16908115611ca2578160ff168381611c9c57fe5b04611ca5565b60005b90506001600160801b03811615611cd757600380546001600160801b03600160801b8083048216850182160291161790555b611cf1818403600160801b8d6001600160801b03166132d9565b60028054909101905550505b8d6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338f8f86866040518085815260200184815260200183815260200182815260200194505050505060405180910390a350506000805460ff60f01b1916600160f01b179055505050505050505050505050565b600080548190600160f01b900460ff16611dca576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19168155611de460073389896141e3565b60038101549091506001600160801b0390811690861611611e055784611e14565b60038101546001600160801b03165b60038201549093506001600160801b03600160801b909104811690851611611e3c5783611e52565b6003810154600160801b90046001600160801b03165b91506001600160801b03831615611eb7576003810180546001600160801b031981166001600160801b03918216869003821617909155611eb7907f00000000000000000000000097d0cfeb4fde54b430307c9482d6f79c761fe9b6908a908616613b86565b6001600160801b03821615611f1d576003810180546001600160801b03600160801b808304821686900382160291811691909117909155611f1d907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2908a908516613b86565b604080516001600160a01b038a1681526001600160801b0380861660208301528416818301529051600288810b92908a900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a4506000805460ff60f01b1916600160f01b17905590969095509350505050565b60076020526000908152604090208054600182015460028301546003909301546001600160801b0392831693919281811691600160801b90041685565b60066020526000908152604090205481565b7f00000000000000000000000000000000000762d10ef955d55b7d038c7a7231cc81565b600054600160f01b900460ff16612054576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9841691638da5cb5b916004808301926020929190829003018186803b1580156120c157600080fd5b505afa1580156120d5573d6000803e3d6000fd5b505050506040513d60208110156120eb57600080fd5b50516001600160a01b0316331461210157600080fd5b60ff82161580612124575060048260ff16101580156121245750600a8260ff1611155b801561214e575060ff8116158061214e575060048160ff161015801561214e5750600a8160ff1611155b61215757600080fd5b60008054610ff0600484901b16840160ff908116600160e81b9081027fffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff841617909355919004167f973d8d92bb299f4af6ce49b52a8adb85ae46b9f214c4c4fc06ac77401237b1336010826040805160ff9390920683168252600f600486901c16602083015286831682820152918516606082015290519081900360800190a150506000805460ff60f01b1916600160f01b17905550565b600080548190600160f01b900460ff16612256576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9841691638da5cb5b916004808301926020929190829003018186803b1580156122c357600080fd5b505afa1580156122d7573d6000803e3d6000fd5b505050506040513d60208110156122ed57600080fd5b50516001600160a01b0316331461230357600080fd5b6003546001600160801b039081169085161161231f578361232c565b6003546001600160801b03165b6003549092506001600160801b03600160801b9091048116908416116123525782612366565b600354600160801b90046001600160801b03165b90506001600160801b038216156123e7576003546001600160801b038381169116141561239557600019909101905b600380546001600160801b031981166001600160801b039182168590038216179091556123e7907f00000000000000000000000097d0cfeb4fde54b430307c9482d6f79c761fe9b69087908516613b86565b6001600160801b0381161561246d576003546001600160801b03828116600160801b90920416141561241857600019015b600380546001600160801b03600160801b80830482168590038216029181169190911790915561246d907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29087908416613b86565b604080516001600160801b0380851682528316602082015281516001600160a01b0388169233927f596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151929081900390910190a36000805460ff60f01b1916600160f01b1790559094909350915050565b6060806124e7612bf0565b61255e6124f2612c27565b858580806020026020016040519081016040528093929190818152602001838360200280828437600092018290525054600454600896959450600160a01b820460020b935061ffff600160b81b8304811693506001600160801b0390911691600160c81b900416614247565b915091509250929050565b600080548190600160f01b900460ff166125b0576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916815560408051608081018252338152600288810b602083015287900b918101919091528190819061260990606081016125fc6001600160801b038a16613f58565b600003600f0b9052613f69565b925092509250816000039450806000039350600085118061262a5750600084115b15612669576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b604080516001600160801b0388168152602081018790528082018690529051600289810b92908b900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a450506000805460ff60f01b1916600160f01b179055509094909350915050565b60008060006126ed612bf0565b6126f785856143a1565b600285810b810b60009081526005602052604080822087840b90930b825281206003830154600681900b9367010000000000000082046001600160a01b0316928492600160d81b810463ffffffff169284929091600160f81b900460ff168061275f57600080fd5b6003820154600681900b985067010000000000000081046001600160a01b03169650600160d81b810463ffffffff169450600160f81b900460ff16806127a457600080fd5b50506040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b810b6020840181905261ffff600160b81b8404811695850195909552600160c81b830485166060850152600160d81b8304909416608084015260ff600160e81b8304811660a0850152600160f01b909204909116151560c08301529093508e810b91900b1215905061284d575093909403965090039350900390506128d0565b8a60020b816020015160020b12156128c1576000612869612c27565b602083015160408401516004546060860151939450600093849361289f936008938893879392916001600160801b031690613389565b9a9003989098039b5050949096039290920396509091030392506128d0915050565b50949093039650039350900390505b9250925092565b7f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98481565b7f00000000000000000000000000000000000000000000000000000000000000c881565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b7f000000000000000000000000000000000000000000000000000000000000271081565b60015481565b60056020526000908152604090208054600182015460028301546003909301546001600160801b03831693600160801b909304600f0b9290600681900b9067010000000000000081046001600160a01b031690600160d81b810463ffffffff1690600160f81b900460ff1688565b6000546001600160a01b031615612a1e576040805162461bcd60e51b8152602060048201526002602482015261414960f01b604482015290519081900360640190fd5b6000612a29826136a5565b9050600080612a41612a39612c27565b60089061446a565b6040805160e0810182526001600160a01b038816808252600288810b6020808501829052600085870181905261ffff898116606088018190529089166080880181905260a08801839052600160c0909801979097528154600160f01b73ffffffffffffffffffffffffffffffffffffffff19909116871762ffffff60a01b1916600160a01b62ffffff9787900b9790971696909602959095177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9091021761ffff60d81b1916600160d81b909602959095177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1692909217909355835191825281019190915281519395509193507f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9592918290030190a150505050565b60008082600281900b620d89e71981612b9957fe5b05029050600083600281900b620d89e881612bb057fe5b0502905060008460020b83830360020b81612bc757fe5b0560010190508062ffffff166001600160801b03801681612be457fe5b0493505050505b919050565b306001600160a01b037f000000000000000000000000a57ef40a7b9ea04c1d571605d968b6d7ec7bfbc01614612c2557600080fd5b565b4290565b60008060008460020b8660020b81612c3f57fe5b05905060008660020b128015612c6657508460020b8660020b81612c5f57fe5b0760020b15155b15612c7057600019015b8315612ce557600080612c82836144b6565b600182810b810b600090815260208d9052604090205460ff83169190911b80016000190190811680151597509294509092509085612cc757888360ff16860302612cda565b88612cd1826144c8565b840360ff168603025b965050505050612d63565b600080612cf4836001016144b6565b91509150600060018260ff166001901b031990506000818b60008660010b60010b8152602001908152602001600020541690508060001415955085612d4657888360ff0360ff16866001010102612d5c565b8883612d5183614568565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b12612d84578260020b612d8c565b8260020b6000035b9050620d89e8811115612dca576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612dde57600160801b612df0565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e24576ffff97272373d413259a46990580e213a0260801c5b6004821615612e43576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e62576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e81576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612ea0576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612ebf576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ede576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612efe576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f1e576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f3e576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f5e576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f7e576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f9e576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612fbe576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fde576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612fff576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561301f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561303e576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561305b576b048a170391f7dc42444e8fa20260801c5b60008460020b131561307657806000198161307257fe5b0490505b64010000000081061561308a57600161308d565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906131245760006130d88989620f42400362ffffff16620f42406132d9565b9050826130f1576130ec8c8c8c6001614652565b6130fe565b6130fe8b8d8c60016146cd565b955085811061310f578a965061311e565b61311b8c8b838661478a565b96505b5061316e565b8161313b576131368b8b8b60006146cd565b613148565b6131488a8c8b6000614652565b935083886000031061315c5789955061316e565b61316b8b8a8a600003856147d6565b95505b6001600160a01b038a81169087161482156131d15780801561318d5750815b6131a35761319e878d8c60016146cd565b6131a5565b855b95508080156131b2575081155b6131c8576131c3878d8c6000614652565b6131ca565b845b945061321b565b8080156131db5750815b6131f1576131ec8c888c6001614652565b6131f3565b855b9550808015613200575081155b613216576132118c888c60006146cd565b613218565b845b94505b8115801561322b57508860000385115b15613237578860000394505b81801561325657508a6001600160a01b0316876001600160a01b031614155b15613265578589039350613282565b61327f868962ffffff168a620f42400362ffffff166141a9565b93505b50505095509550955095915050565b6000600160ff1b82106132a357600080fd5b5090565b808203828113156000831215146132bd57600080fd5b92915050565b818101828112156000831215146132bd57600080fd5b600080806000198587098686029250828110908390030390508061330f576000841161330457600080fd5b508290049050613382565b80841161331b57600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008063ffffffff8716613430576000898661ffff1661ffff81106133aa57fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a161461341c57613419818a8988614822565b90505b806020015181604001519250925050613510565b8688036000806134458c8c858c8c8c8c6148d2565b91509150816000015163ffffffff168363ffffffff161415613477578160200151826040015194509450505050613510565b805163ffffffff8481169116141561349f578060200151816040015194509450505050613510565b8151815160208085015190840151918390039286039163ffffffff80841692908516910360060b816134cd57fe5b05028460200151018263ffffffff168263ffffffff1686604001518660400151036001600160a01b031602816134ff57fe5b048560400151019650965050505050505b97509795505050505050565b600295860b860b60009081526020979097526040909620600181018054909503909455938301805490920390915560038201805463ffffffff600160d81b6001600160a01b036701000000000000008085048216909603169094027fffffffffff0000000000000000000000000000000000000000ffffffffffffff90921691909117600681810b90960390950b66ffffffffffffff1666ffffffffffffff199095169490941782810485169095039093160263ffffffff60d81b1990931692909217905554600160801b9004600f0b90565b60008082600f0b121561365457826001600160801b03168260000384039150816001600160801b03161061364f576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b6132bd565b826001600160801b03168284019150816001600160801b031610156132bd576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b038316108015906136e1575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613716576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106137b757607f810383901c91506137c1565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146139c257886001600160a01b03166139a682612d6d565b6001600160a01b031611156139bb57816139bd565b805b6139c4565b815b9998505050505050505050565b6000806000898961ffff1661ffff81106139e757fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff161515606083015290925089161415613a575788859250925050613510565b8461ffff168461ffff16118015613a7857506001850361ffff168961ffff16145b15613a8557839150613a89565b8491505b8161ffff168960010161ffff1681613a9d57fe5b069250613aac81898989614822565b8a8461ffff1661ffff8110613abd57fe5b825191018054602084015160408501516060909501511515600160f81b027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b03909616600160581b027fff0000000000000000000000000000000000000000ffffffffffffffffffffff60069390930b66ffffffffffffff16640100000000026affffffffffffff000000001963ffffffff90971663ffffffff199095169490941795909516929092171692909217929092161790555097509795505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c025780518252601f199092019160209182019101613be3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c64576040519150601f19603f3d011682016040523d82523d6000602084013e613c69565b606091505b5091509150818015613c97575080511580613c975750808060200190516020811015613c9457600080fd5b50515b613ccd576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b5050505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f00000000000000000000000097d0cfeb4fde54b430307c9482d6f79c761fe9b61693919290918291908083835b60208310613d6d5780518252601f199092019160209182019101613d4e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613dcd576040519150601f19603f3d011682016040523d82523d6000602084013e613dd2565b606091505b5091509150818015613de657506020815110155b613def57600080fd5b808060200190516020811015613e0457600080fd5b50519250505090565b808201828110156132bd57600080fd5b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216939192909182919080838360208310613d6d5780518252601f199092019160209182019101613d4e565b6000808361ffff1611613ef3576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b8261ffff168261ffff1611613f09575081613382565b825b8261ffff168161ffff161015613f4f576001858261ffff1661ffff8110613f2e57fe5b01805463ffffffff191663ffffffff92909216919091179055600101613f0b565b50909392505050565b80600f81900b8114612beb57600080fd5b6000806000613f76612bf0565b613f88846020015185604001516143a1565b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602080840182905261ffff600160b81b8404811685870152600160c81b84048116606080870191909152600160d81b8504909116608086015260ff600160e81b8504811660a0870152600160f01b909404909316151560c08501528851908901519489015192890151939461402c9491939092909190614acf565b93508460600151600f0b6000146141a157846020015160020b816020015160020b12156140815761407a6140638660200151612d6d565b6140708760400151612d6d565b8760600151614c84565b92506141a1565b846040015160020b816020015160020b12156141775760045460408201516001600160801b03909116906140d3906140b7612c27565b60208501516060860151608087015160089493929187916139d1565b6000805461ffff60c81b1916600160c81b61ffff938416021761ffff60b81b1916600160b81b939092169290920217905581516040870151614123919061411990612d6d565b8860600151614c84565b93506141416141358760200151612d6d565b83516060890151614cc8565b92506141518187606001516135ef565b600480546001600160801b0319166001600160801b0392909216919091179055506141a1565b61419e6141878660200151612d6d565b6141948760400151612d6d565b8760600151614cc8565b91505b509193909250565b60006141b68484846132d9565b9050600082806141c257fe5b84860911156133825760001981106141d957600080fd5b6001019392505050565b6040805160609490941b6bffffffffffffffffffffffff1916602080860191909152600293840b60e890811b60348701529290930b90911b60378401528051808403601a018152603a90930181528251928201929092206000908152929052902090565b60608060008361ffff1611614287576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b865167ffffffffffffffff8111801561429f57600080fd5b506040519080825280602002602001820160405280156142c9578160200160208202803683370190505b509150865167ffffffffffffffff811180156142e457600080fd5b5060405190808252806020026020018201604052801561430e578160200160208202803683370190505b50905060005b87518110156143945761433f8a8a8a848151811061432e57fe5b60200260200101518a8a8a8a613389565b84838151811061434b57fe5b6020026020010184848151811061435e57fe5b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b81525050508080600101915050614314565b5097509795505050505050565b8060020b8260020b126143e1576040805162461bcd60e51b8152602060048201526003602482015262544c5560e81b604482015290519081900360640190fd5b620d89e719600283900b1215614424576040805162461bcd60e51b8152602060048201526003602482015262544c4d60e81b604482015290519081900360640190fd5b620d89e8600282900b1315614466576040805162461bcd60e51b815260206004820152600360248201526254554d60e81b604482015290519081900360640190fd5b5050565b6040805160808101825263ffffffff9283168082526000602083018190529282019290925260016060909101819052835463ffffffff1916909117909116600160f81b17909155908190565b60020b600881901d9161010090910790565b60008082116144d657600080fd5b600160801b82106144e957608091821c91015b68010000000000000000821061450157604091821c91015b640100000000821061451557602091821c91015b62010000821061452757601091821c91015b610100821061453857600891821c91015b6010821061454857600491821c91015b6004821061455857600291821c91015b60028210612beb57600101919050565b600080821161457657600080fd5b5060ff6001600160801b0382161561459157607f1901614599565b608082901c91505b67ffffffffffffffff8216156145b257603f19016145ba565b604082901c91505b63ffffffff8216156145cf57601f19016145d7565b602082901c91505b61ffff8216156145ea57600f19016145f2565b601082901c91505b60ff821615614604576007190161460c565b600882901c91505b600f82161561461e5760031901614626565b600482901c91505b60038216156146385760011901614640565b600282901c91505b6001821615612beb5760001901919050565b6000836001600160a01b0316856001600160a01b03161115614672579293925b8161469f5761469a836001600160801b03168686036001600160a01b0316600160601b6132d9565b6146c2565b6146c2836001600160801b03168686036001600160a01b0316600160601b6141a9565b90505b949350505050565b6000836001600160a01b0316856001600160a01b031611156146ed579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661472957600080fd5b8361475957866001600160a01b031661474c8383896001600160a01b03166132d9565b8161475357fe5b0461477f565b61477f6147708383896001600160a01b03166141a9565b886001600160a01b0316614cf7565b979650505050505050565b600080856001600160a01b0316116147a157600080fd5b6000846001600160801b0316116147b757600080fd5b816147c95761469a8585856001614d02565b6146c28585856001614de3565b600080856001600160a01b0316116147ed57600080fd5b6000846001600160801b03161161480357600080fd5b816148155761469a8585856000614de3565b6146c28585856000614d02565b61482a61564a565b600085600001518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020016000856001600160801b03161161487e576001614880565b845b6001600160801b031673ffffffff00000000000000000000000000000000608085901b16816148ab57fe5b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b6148da61564a565b6148e261564a565b888561ffff1661ffff81106148f357fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff1615156060820152925061495890899089614ed8565b15614990578663ffffffff16826000015163ffffffff16141561497a57613510565b8161498783898988614822565b91509150613510565b888361ffff168660010161ffff16816149a557fe5b0661ffff1661ffff81106149b557fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909250614a6c57604080516080810182528a5463ffffffff811682526401000000008104600690810b810b900b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b614a7b88836000015189614ed8565b614ab2576040805162461bcd60e51b815260206004820152600360248201526213d31160ea1b604482015290519081900360640190fd5b614abf8989898887614f9b565b9150915097509795505050505050565b6000614ade60078787876141e3565b60015460025491925090600080600f87900b15614c24576000614aff612c27565b6000805460045492935090918291614b499160089186918591600160a01b810460020b9161ffff600160b81b83048116926001600160801b0390921691600160c81b900416613389565b9092509050614b8360058d8b8d8b8b87898b60007f00000000000000000000000000000000000762d10ef955d55b7d038c7a7231cc61513b565b9450614bba60058c8b8d8b8b87898b60017f00000000000000000000000000000000000762d10ef955d55b7d038c7a7231cc61513b565b93508415614bee57614bee60068d7f00000000000000000000000000000000000000000000000000000000000000c8615325565b8315614c2057614c2060068c7f00000000000000000000000000000000000000000000000000000000000000c8615325565b5050505b600080614c3660058c8c8b8a8a61538b565b9092509050614c47878a8484615437565b600089600f0b1215614c75578315614c6457614c6460058c6155cc565b8215614c7557614c7560058b6155cc565b50505050505095945050505050565b60008082600f0b12614caa57614ca5614ca085858560016146cd565b613291565b6146c5565b614cbd614ca085858560000360006146cd565b600003949350505050565b60008082600f0b12614ce457614ca5614ca08585856001614652565b614cbd614ca08585856000036000614652565b808204910615150190565b60008115614d755760006001600160a01b03841115614d3857614d3384600160601b876001600160801b03166132d9565b614d50565b6001600160801b038516606085901b81614d4e57fe5b045b9050614d6d614d686001600160a01b03881683613e0d565b6155f8565b9150506146c5565b60006001600160a01b03841115614da357614d9e84600160601b876001600160801b03166141a9565b614dba565b614dba606085901b6001600160801b038716614cf7565b905080866001600160a01b031611614dd157600080fd5b6001600160a01b0386160390506146c5565b600082614df15750836146c5565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b168215614e91576001600160a01b03861684810290858281614e3157fe5b041415614e6257818101828110614e6057614e5683896001600160a01b0316836141a9565b93505050506146c5565b505b614e8882614e83878a6001600160a01b03168681614e7c57fe5b0490613e0d565b614cf7565b925050506146c5565b6001600160a01b03861684810290858281614ea857fe5b04148015614eb557508082115b614ebe57600080fd5b808203614e56614d68846001600160a01b038b16846141a9565b60008363ffffffff168363ffffffff1611158015614f0257508363ffffffff168263ffffffff1611155b15614f1e578163ffffffff168363ffffffff1611159050613382565b60008463ffffffff168463ffffffff1611614f46578363ffffffff1664010000000001614f4e565b8363ffffffff165b64ffffffffff16905060008563ffffffff168463ffffffff1611614f7f578363ffffffff1664010000000001614f87565b8363ffffffff165b64ffffffffff169091111595945050505050565b614fa361564a565b614fab61564a565b60008361ffff168560010161ffff1681614fc157fe5b0661ffff169050600060018561ffff16830103905060005b506002818301048961ffff87168281614fee57fe5b0661ffff8110614ffa57fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290955061506557806001019250614fd9565b898661ffff16826001018161507657fe5b0661ffff811061508257fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094506000906150ed908b908b614ed8565b905080801561510657506151068a8a8760000151614ed8565b15615111575061512e565b8061512157600182039250615128565b8160010193505b50614fd9565b5050509550959350505050565b60028a810b900b600090815260208c90526040812080546001600160801b031682615166828d6135ef565b9050846001600160801b0316816001600160801b031611156151b4576040805162461bcd60e51b81526020600482015260026024820152614c4f60f01b604482015290519081900360640190fd5b6001600160801b03828116159082161581141594501561528a578c60020b8e60020b1361525a57600183018b9055600283018a90556003830180547fffffffffff0000000000000000000000000000000000000000ffffffffffffff166701000000000000006001600160a01b038c16021766ffffffffffffff191666ffffffffffffff60068b900b161763ffffffff60d81b1916600160d81b63ffffffff8a16021790555b6003830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b038216178355856152d35782546152ce906152c990600160801b9004600f90810b810b908f900b6132c3565b613f58565b6152f4565b82546152f4906152c990600160801b9004600f90810b810b908f900b6132a7565b8354600f9190910b6001600160801b03908116600160801b0291161790925550909c9b505050505050505050505050565b8060020b8260020b8161533457fe5b0760020b1561534257600080fd5b60008061535d8360020b8560020b8161535757fe5b056144b6565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b126153d1575050600182015460028301546153e4565b8360010154880391508360020154870390505b6000808b60020b8b60020b121561540657505060018301546002840154615419565b84600101548a0391508460020154890390505b92909803979097039b96909503949094039850939650505050505050565b6040805160a08101825285546001600160801b0390811682526001870154602083015260028701549282019290925260038601548083166060830152600160801b900490911660808201526000600f85900b6154d65781516001600160801b03166154ce576040805162461bcd60e51b815260206004820152600260248201526104e560f41b604482015290519081900360640190fd5b5080516154e5565b81516154e290866135ef565b90505b60006155098360200151860384600001516001600160801b0316600160801b6132d9565b9050600061552f8460400151860385600001516001600160801b0316600160801b6132d9565b905086600f0b6000146155565787546001600160801b0319166001600160801b0384161788555b60018801869055600288018590556001600160801b03821615158061558457506000816001600160801b0316115b156155c2576003880180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b5050505050505050565b600290810b810b6000908152602092909252604082208281556001810183905590810182905560030155565b806001600160a01b0381168114612beb57600080fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160808101825260008082526020820181905291810182905260608101919091529056fea164736f6c6343000706000a
|
{{
"language": "Solidity",
"sources": {
"contracts/UniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.7.6;\n\nimport './interfaces/IUniswapV3Pool.sol';\n\nimport './NoDelegateCall.sol';\n\nimport './libraries/LowGasSafeMath.sol';\nimport './libraries/SafeCast.sol';\nimport './libraries/Tick.sol';\nimport './libraries/TickBitmap.sol';\nimport './libraries/Position.sol';\nimport './libraries/Oracle.sol';\n\nimport './libraries/FullMath.sol';\nimport './libraries/FixedPoint128.sol';\nimport './libraries/TransferHelper.sol';\nimport './libraries/TickMath.sol';\nimport './libraries/LiquidityMath.sol';\nimport './libraries/SqrtPriceMath.sol';\nimport './libraries/SwapMath.sol';\n\nimport './interfaces/IUniswapV3PoolDeployer.sol';\nimport './interfaces/IUniswapV3Factory.sol';\nimport './interfaces/IERC20Minimal.sol';\nimport './interfaces/callback/IUniswapV3MintCallback.sol';\nimport './interfaces/callback/IUniswapV3SwapCallback.sol';\nimport './interfaces/callback/IUniswapV3FlashCallback.sol';\n\ncontract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Tick for mapping(int24 => Tick.Info);\n using TickBitmap for mapping(int16 => uint256);\n using Position for mapping(bytes32 => Position.Info);\n using Position for Position.Info;\n using Oracle for Oracle.Observation[65535];\n\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override factory;\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override token0;\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override token1;\n /// @inheritdoc IUniswapV3PoolImmutables\n uint24 public immutable override fee;\n\n /// @inheritdoc IUniswapV3PoolImmutables\n int24 public immutable override tickSpacing;\n\n /// @inheritdoc IUniswapV3PoolImmutables\n uint128 public immutable override maxLiquidityPerTick;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n /// @inheritdoc IUniswapV3PoolState\n Slot0 public override slot0;\n\n /// @inheritdoc IUniswapV3PoolState\n uint256 public override feeGrowthGlobal0X128;\n /// @inheritdoc IUniswapV3PoolState\n uint256 public override feeGrowthGlobal1X128;\n\n // accumulated protocol fees in token0/token1 units\n struct ProtocolFees {\n uint128 token0;\n uint128 token1;\n }\n /// @inheritdoc IUniswapV3PoolState\n ProtocolFees public override protocolFees;\n\n /// @inheritdoc IUniswapV3PoolState\n uint128 public override liquidity;\n\n /// @inheritdoc IUniswapV3PoolState\n mapping(int24 => Tick.Info) public override ticks;\n /// @inheritdoc IUniswapV3PoolState\n mapping(int16 => uint256) public override tickBitmap;\n /// @inheritdoc IUniswapV3PoolState\n mapping(bytes32 => Position.Info) public override positions;\n /// @inheritdoc IUniswapV3PoolState\n Oracle.Observation[65535] public override observations;\n\n /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance\n /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because\n /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.\n modifier lock() {\n require(slot0.unlocked, 'LOK');\n slot0.unlocked = false;\n _;\n slot0.unlocked = true;\n }\n\n /// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner()\n modifier onlyFactoryOwner() {\n require(msg.sender == IUniswapV3Factory(factory).owner());\n _;\n }\n\n constructor() {\n int24 _tickSpacing;\n (factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters();\n tickSpacing = _tickSpacing;\n\n maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);\n }\n\n /// @dev Common checks for valid tick inputs.\n function checkTicks(int24 tickLower, int24 tickUpper) private pure {\n require(tickLower < tickUpper, 'TLU');\n require(tickLower >= TickMath.MIN_TICK, 'TLM');\n require(tickUpper <= TickMath.MAX_TICK, 'TUM');\n }\n\n /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.\n function _blockTimestamp() internal view virtual returns (uint32) {\n return uint32(block.timestamp); // truncation is desired\n }\n\n /// @dev Get the pool's balance of token0\n /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n /// check\n function balance0() private view returns (uint256) {\n (bool success, bytes memory data) =\n token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));\n require(success && data.length >= 32);\n return abi.decode(data, (uint256));\n }\n\n /// @dev Get the pool's balance of token1\n /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n /// check\n function balance1() private view returns (uint256) {\n (bool success, bytes memory data) =\n token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));\n require(success && data.length >= 32);\n return abi.decode(data, (uint256));\n }\n\n /// @inheritdoc IUniswapV3PoolDerivedState\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n override\n noDelegateCall\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n )\n {\n checkTicks(tickLower, tickUpper);\n\n int56 tickCumulativeLower;\n int56 tickCumulativeUpper;\n uint160 secondsPerLiquidityOutsideLowerX128;\n uint160 secondsPerLiquidityOutsideUpperX128;\n uint32 secondsOutsideLower;\n uint32 secondsOutsideUpper;\n\n {\n Tick.Info storage lower = ticks[tickLower];\n Tick.Info storage upper = ticks[tickUpper];\n bool initializedLower;\n (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (\n lower.tickCumulativeOutside,\n lower.secondsPerLiquidityOutsideX128,\n lower.secondsOutside,\n lower.initialized\n );\n require(initializedLower);\n\n bool initializedUpper;\n (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (\n upper.tickCumulativeOutside,\n upper.secondsPerLiquidityOutsideX128,\n upper.secondsOutside,\n upper.initialized\n );\n require(initializedUpper);\n }\n\n Slot0 memory _slot0 = slot0;\n\n if (_slot0.tick < tickLower) {\n return (\n tickCumulativeLower - tickCumulativeUpper,\n secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,\n secondsOutsideLower - secondsOutsideUpper\n );\n } else if (_slot0.tick < tickUpper) {\n uint32 time = _blockTimestamp();\n (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =\n observations.observeSingle(\n time,\n 0,\n _slot0.tick,\n _slot0.observationIndex,\n liquidity,\n _slot0.observationCardinality\n );\n return (\n tickCumulative - tickCumulativeLower - tickCumulativeUpper,\n secondsPerLiquidityCumulativeX128 -\n secondsPerLiquidityOutsideLowerX128 -\n secondsPerLiquidityOutsideUpperX128,\n time - secondsOutsideLower - secondsOutsideUpper\n );\n } else {\n return (\n tickCumulativeUpper - tickCumulativeLower,\n secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,\n secondsOutsideUpper - secondsOutsideLower\n );\n }\n }\n\n /// @inheritdoc IUniswapV3PoolDerivedState\n function observe(uint32[] calldata secondsAgos)\n external\n view\n override\n noDelegateCall\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n return\n observations.observe(\n _blockTimestamp(),\n secondsAgos,\n slot0.tick,\n slot0.observationIndex,\n liquidity,\n slot0.observationCardinality\n );\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext)\n external\n override\n lock\n noDelegateCall\n {\n uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event\n uint16 observationCardinalityNextNew =\n observations.grow(observationCardinalityNextOld, observationCardinalityNext);\n slot0.observationCardinalityNext = observationCardinalityNextNew;\n if (observationCardinalityNextOld != observationCardinalityNextNew)\n emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev not locked because it initializes unlocked\n function initialize(uint160 sqrtPriceX96) external override {\n require(slot0.sqrtPriceX96 == 0, 'AI');\n\n int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);\n\n (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());\n\n slot0 = Slot0({\n sqrtPriceX96: sqrtPriceX96,\n tick: tick,\n observationIndex: 0,\n observationCardinality: cardinality,\n observationCardinalityNext: cardinalityNext,\n feeProtocol: 0,\n unlocked: true\n });\n\n emit Initialize(sqrtPriceX96, tick);\n }\n\n struct ModifyPositionParams {\n // the address that owns the position\n address owner;\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // any change in liquidity\n int128 liquidityDelta;\n }\n\n /// @dev Effect some changes to a position\n /// @param params the position details and the change to the position's liquidity to effect\n /// @return position a storage pointer referencing the position with the given owner and tick range\n /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient\n /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient\n function _modifyPosition(ModifyPositionParams memory params)\n private\n noDelegateCall\n returns (\n Position.Info storage position,\n int256 amount0,\n int256 amount1\n )\n {\n checkTicks(params.tickLower, params.tickUpper);\n\n Slot0 memory _slot0 = slot0; // SLOAD for gas optimization\n\n position = _updatePosition(\n params.owner,\n params.tickLower,\n params.tickUpper,\n params.liquidityDelta,\n _slot0.tick\n );\n\n if (params.liquidityDelta != 0) {\n if (_slot0.tick < params.tickLower) {\n // current tick is below the passed range; liquidity can only become in range by crossing from left to\n // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it\n amount0 = SqrtPriceMath.getAmount0Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n } else if (_slot0.tick < params.tickUpper) {\n // current tick is inside the passed range\n uint128 liquidityBefore = liquidity; // SLOAD for gas optimization\n\n // write an oracle entry\n (slot0.observationIndex, slot0.observationCardinality) = observations.write(\n _slot0.observationIndex,\n _blockTimestamp(),\n _slot0.tick,\n liquidityBefore,\n _slot0.observationCardinality,\n _slot0.observationCardinalityNext\n );\n\n amount0 = SqrtPriceMath.getAmount0Delta(\n _slot0.sqrtPriceX96,\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n amount1 = SqrtPriceMath.getAmount1Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n _slot0.sqrtPriceX96,\n params.liquidityDelta\n );\n\n liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);\n } else {\n // current tick is above the passed range; liquidity can only become in range by crossing from right to\n // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it\n amount1 = SqrtPriceMath.getAmount1Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n }\n }\n }\n\n /// @dev Gets and updates a position with the given liquidity delta\n /// @param owner the owner of the position\n /// @param tickLower the lower tick of the position's tick range\n /// @param tickUpper the upper tick of the position's tick range\n /// @param tick the current tick, passed to avoid sloads\n function _updatePosition(\n address owner,\n int24 tickLower,\n int24 tickUpper,\n int128 liquidityDelta,\n int24 tick\n ) private returns (Position.Info storage position) {\n position = positions.get(owner, tickLower, tickUpper);\n\n uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization\n uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization\n\n // if we need to update the ticks, do it\n bool flippedLower;\n bool flippedUpper;\n if (liquidityDelta != 0) {\n uint32 time = _blockTimestamp();\n (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =\n observations.observeSingle(\n time,\n 0,\n slot0.tick,\n slot0.observationIndex,\n liquidity,\n slot0.observationCardinality\n );\n\n flippedLower = ticks.update(\n tickLower,\n tick,\n liquidityDelta,\n _feeGrowthGlobal0X128,\n _feeGrowthGlobal1X128,\n secondsPerLiquidityCumulativeX128,\n tickCumulative,\n time,\n false,\n maxLiquidityPerTick\n );\n flippedUpper = ticks.update(\n tickUpper,\n tick,\n liquidityDelta,\n _feeGrowthGlobal0X128,\n _feeGrowthGlobal1X128,\n secondsPerLiquidityCumulativeX128,\n tickCumulative,\n time,\n true,\n maxLiquidityPerTick\n );\n\n if (flippedLower) {\n tickBitmap.flipTick(tickLower, tickSpacing);\n }\n if (flippedUpper) {\n tickBitmap.flipTick(tickUpper, tickSpacing);\n }\n }\n\n (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =\n ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128);\n\n position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);\n\n // clear any tick data that is no longer needed\n if (liquidityDelta < 0) {\n if (flippedLower) {\n ticks.clear(tickLower);\n }\n if (flippedUpper) {\n ticks.clear(tickUpper);\n }\n }\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev noDelegateCall is applied indirectly via _modifyPosition\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external override lock returns (uint256 amount0, uint256 amount1) {\n require(amount > 0);\n (, int256 amount0Int, int256 amount1Int) =\n _modifyPosition(\n ModifyPositionParams({\n owner: recipient,\n tickLower: tickLower,\n tickUpper: tickUpper,\n liquidityDelta: int256(amount).toInt128()\n })\n );\n\n amount0 = uint256(amount0Int);\n amount1 = uint256(amount1Int);\n\n uint256 balance0Before;\n uint256 balance1Before;\n if (amount0 > 0) balance0Before = balance0();\n if (amount1 > 0) balance1Before = balance1();\n IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);\n if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');\n if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');\n\n emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external override lock returns (uint128 amount0, uint128 amount1) {\n // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}\n Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);\n\n amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;\n amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;\n\n if (amount0 > 0) {\n position.tokensOwed0 -= amount0;\n TransferHelper.safeTransfer(token0, recipient, amount0);\n }\n if (amount1 > 0) {\n position.tokensOwed1 -= amount1;\n TransferHelper.safeTransfer(token1, recipient, amount1);\n }\n\n emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev noDelegateCall is applied indirectly via _modifyPosition\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external override lock returns (uint256 amount0, uint256 amount1) {\n (Position.Info storage position, int256 amount0Int, int256 amount1Int) =\n _modifyPosition(\n ModifyPositionParams({\n owner: msg.sender,\n tickLower: tickLower,\n tickUpper: tickUpper,\n liquidityDelta: -int256(amount).toInt128()\n })\n );\n\n amount0 = uint256(-amount0Int);\n amount1 = uint256(-amount1Int);\n\n if (amount0 > 0 || amount1 > 0) {\n (position.tokensOwed0, position.tokensOwed1) = (\n position.tokensOwed0 + uint128(amount0),\n position.tokensOwed1 + uint128(amount1)\n );\n }\n\n emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external override noDelegateCall returns (int256 amount0, int256 amount1) {\n require(amountSpecified != 0, 'AS');\n\n Slot0 memory slot0Start = slot0;\n\n require(slot0Start.unlocked, 'LOK');\n require(\n zeroForOne\n ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO\n : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,\n 'SPL'\n );\n\n slot0.unlocked = false;\n\n SwapCache memory cache =\n SwapCache({\n liquidityStart: liquidity,\n blockTimestamp: _blockTimestamp(),\n feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4),\n secondsPerLiquidityCumulativeX128: 0,\n tickCumulative: 0,\n computedLatestObservation: false\n });\n\n bool exactInput = amountSpecified > 0;\n\n SwapState memory state =\n SwapState({\n amountSpecifiedRemaining: amountSpecified,\n amountCalculated: 0,\n sqrtPriceX96: slot0Start.sqrtPriceX96,\n tick: slot0Start.tick,\n feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,\n protocolFee: 0,\n liquidity: cache.liquidityStart\n });\n\n // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(\n state.tick,\n tickSpacing,\n zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)\n ? sqrtPriceLimitX96\n : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n fee\n );\n\n if (exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee\n if (cache.feeProtocol > 0) {\n uint256 delta = step.feeAmount / cache.feeProtocol;\n step.feeAmount -= delta;\n state.protocolFee += uint128(delta);\n }\n\n // update global fee tracker\n if (state.liquidity > 0)\n state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n // check for the placeholder value, which we replace with the actual value the first time the swap\n // crosses an initialized tick\n if (!cache.computedLatestObservation) {\n (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(\n cache.blockTimestamp,\n 0,\n slot0Start.tick,\n slot0Start.observationIndex,\n cache.liquidityStart,\n slot0Start.observationCardinality\n );\n cache.computedLatestObservation = true;\n }\n int128 liquidityNet =\n ticks.cross(\n step.tickNext,\n (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),\n (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),\n cache.secondsPerLiquidityCumulativeX128,\n cache.tickCumulative,\n cache.blockTimestamp\n );\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n }\n\n state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n // update tick and write an oracle entry if the tick change\n if (state.tick != slot0Start.tick) {\n (uint16 observationIndex, uint16 observationCardinality) =\n observations.write(\n slot0Start.observationIndex,\n cache.blockTimestamp,\n slot0Start.tick,\n cache.liquidityStart,\n slot0Start.observationCardinality,\n slot0Start.observationCardinalityNext\n );\n (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (\n state.sqrtPriceX96,\n state.tick,\n observationIndex,\n observationCardinality\n );\n } else {\n // otherwise just update the price\n slot0.sqrtPriceX96 = state.sqrtPriceX96;\n }\n\n // update liquidity if it changed\n if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;\n\n // update fee growth global and, if necessary, protocol fees\n // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees\n if (zeroForOne) {\n feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;\n if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;\n } else {\n feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;\n if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;\n }\n\n (amount0, amount1) = zeroForOne == exactInput\n ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);\n\n // do the transfers and collect payment\n if (zeroForOne) {\n if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));\n\n uint256 balance0Before = balance0();\n IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);\n require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');\n } else {\n if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));\n\n uint256 balance1Before = balance1();\n IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);\n require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');\n }\n\n emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick);\n slot0.unlocked = true;\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external override lock noDelegateCall {\n uint128 _liquidity = liquidity;\n require(_liquidity > 0, 'L');\n\n uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);\n uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);\n uint256 balance0Before = balance0();\n uint256 balance1Before = balance1();\n\n if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);\n if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);\n\n IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);\n\n uint256 balance0After = balance0();\n uint256 balance1After = balance1();\n\n require(balance0Before.add(fee0) <= balance0After, 'F0');\n require(balance1Before.add(fee1) <= balance1After, 'F1');\n\n // sub is safe because we know balanceAfter is gt balanceBefore by at least fee\n uint256 paid0 = balance0After - balance0Before;\n uint256 paid1 = balance1After - balance1Before;\n\n if (paid0 > 0) {\n uint8 feeProtocol0 = slot0.feeProtocol % 16;\n uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0;\n if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);\n feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);\n }\n if (paid1 > 0) {\n uint8 feeProtocol1 = slot0.feeProtocol >> 4;\n uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1;\n if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);\n feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);\n }\n\n emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);\n }\n\n /// @inheritdoc IUniswapV3PoolOwnerActions\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {\n require(\n (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&\n (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))\n );\n uint8 feeProtocolOld = slot0.feeProtocol;\n slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);\n emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);\n }\n\n /// @inheritdoc IUniswapV3PoolOwnerActions\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) {\n amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;\n amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;\n\n if (amount0 > 0) {\n if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings\n protocolFees.token0 -= amount0;\n TransferHelper.safeTransfer(token0, recipient, amount0);\n }\n if (amount1 > 0) {\n if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings\n protocolFees.token1 -= amount1;\n TransferHelper.safeTransfer(token1, recipient, amount1);\n }\n\n emit CollectProtocol(msg.sender, recipient, amount0, amount1);\n }\n}\n"
},
"contracts/interfaces/IUniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n IUniswapV3PoolImmutables,\n IUniswapV3PoolState,\n IUniswapV3PoolDerivedState,\n IUniswapV3PoolActions,\n IUniswapV3PoolOwnerActions,\n IUniswapV3PoolEvents\n{\n\n}\n"
},
"contracts/NoDelegateCall.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.7.6;\n\n/// @title Prevents delegatecall to a contract\n/// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract\nabstract contract NoDelegateCall {\n /// @dev The original address of this contract\n address private immutable original;\n\n constructor() {\n // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.\n // In other words, this variable won't change when it's checked at runtime.\n original = address(this);\n }\n\n /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,\n /// and the use of immutable means the address bytes are copied in every place the modifier is used.\n function checkNotDelegateCall() private view {\n require(address(this) == original);\n }\n\n /// @notice Prevents delegatecall into the modified method\n modifier noDelegateCall() {\n checkNotDelegateCall();\n _;\n }\n}\n"
},
"contracts/libraries/LowGasSafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.0;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary LowGasSafeMath {\n /// @notice Returns x + y, reverts if sum overflows uint256\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x + y) >= x);\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x - y) <= x);\n }\n\n /// @notice Returns x * y, reverts if overflows\n /// @param x The multiplicand\n /// @param y The multiplier\n /// @return z The product of x and y\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require(x == 0 || (z = x * y) / x == y);\n }\n\n /// @notice Returns x + y, reverts if overflows or underflows\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x + y) >= x == (y >= 0));\n }\n\n /// @notice Returns x - y, reverts if overflows or underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x - y) <= x == (y >= 0));\n }\n}\n"
},
"contracts/libraries/SafeCast.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\n }\n}\n"
},
"contracts/libraries/Tick.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './TickMath.sol';\nimport './LiquidityMath.sol';\n\n/// @title Tick\n/// @notice Contains functions for managing tick processes and relevant calculations\nlibrary Tick {\n using LowGasSafeMath for int256;\n using SafeCast for int256;\n\n // info stored for each initialized individual tick\n struct Info {\n // the total position liquidity that references this tick\n uint128 liquidityGross;\n // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),\n int128 liquidityNet;\n // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint256 feeGrowthOutside0X128;\n uint256 feeGrowthOutside1X128;\n // the cumulative tick value on the other side of the tick\n int56 tickCumulativeOutside;\n // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint160 secondsPerLiquidityOutsideX128;\n // the seconds spent on the other side of the tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint32 secondsOutside;\n // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0\n // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks\n bool initialized;\n }\n\n /// @notice Derives max liquidity per tick from given tick spacing\n /// @dev Executed within the pool constructor\n /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`\n /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...\n /// @return The max liquidity per tick\n function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {\n int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;\n int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;\n uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;\n return type(uint128).max / numTicks;\n }\n\n /// @notice Retrieves fee growth data\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param tickCurrent The current tick\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function getFeeGrowthInside(\n mapping(int24 => Tick.Info) storage self,\n int24 tickLower,\n int24 tickUpper,\n int24 tickCurrent,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128\n ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {\n Info storage lower = self[tickLower];\n Info storage upper = self[tickUpper];\n\n // calculate fee growth below\n uint256 feeGrowthBelow0X128;\n uint256 feeGrowthBelow1X128;\n if (tickCurrent >= tickLower) {\n feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;\n } else {\n feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;\n }\n\n // calculate fee growth above\n uint256 feeGrowthAbove0X128;\n uint256 feeGrowthAbove1X128;\n if (tickCurrent < tickUpper) {\n feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;\n } else {\n feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;\n }\n\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;\n }\n\n /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tick The tick that will be updated\n /// @param tickCurrent The current tick\n /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool\n /// @param time The current block timestamp cast to a uint32\n /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick\n /// @param maxLiquidity The maximum liquidity allocation for a single tick\n /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa\n function update(\n mapping(int24 => Tick.Info) storage self,\n int24 tick,\n int24 tickCurrent,\n int128 liquidityDelta,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time,\n bool upper,\n uint128 maxLiquidity\n ) internal returns (bool flipped) {\n Tick.Info storage info = self[tick];\n\n uint128 liquidityGrossBefore = info.liquidityGross;\n uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);\n\n require(liquidityGrossAfter <= maxLiquidity, 'LO');\n\n flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);\n\n if (liquidityGrossBefore == 0) {\n // by convention, we assume that all growth before a tick was initialized happened _below_ the tick\n if (tick <= tickCurrent) {\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;\n info.tickCumulativeOutside = tickCumulative;\n info.secondsOutside = time;\n }\n info.initialized = true;\n }\n\n info.liquidityGross = liquidityGrossAfter;\n\n // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)\n info.liquidityNet = upper\n ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()\n : int256(info.liquidityNet).add(liquidityDelta).toInt128();\n }\n\n /// @notice Clears tick data\n /// @param self The mapping containing all initialized tick information for initialized ticks\n /// @param tick The tick that will be cleared\n function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {\n delete self[tick];\n }\n\n /// @notice Transitions to next tick as needed by price movement\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tick The destination tick of the transition\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity\n /// @param time The current block.timestamp\n /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function cross(\n mapping(int24 => Tick.Info) storage self,\n int24 tick,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time\n ) internal returns (int128 liquidityNet) {\n Tick.Info storage info = self[tick];\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;\n info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;\n info.secondsOutside = time - info.secondsOutside;\n liquidityNet = info.liquidityNet;\n }\n}\n"
},
"contracts/libraries/TickBitmap.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './BitMath.sol';\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary TickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(tick % 256);\n }\n\n /// @notice Flips the initialized state for a given tick from false to true, or vice versa\n /// @param self The mapping in which to flip the tick\n /// @param tick The tick to flip\n /// @param tickSpacing The spacing between usable ticks\n function flipTick(\n mapping(int16 => uint256) storage self,\n int24 tick,\n int24 tickSpacing\n ) internal {\n require(tick % tickSpacing == 0); // ensure that the tick is spaced\n (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);\n uint256 mask = 1 << bitPos;\n self[wordPos] ^= mask;\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param self The mapping in which to compute the next initialized tick\n /// @param tick The starting tick\n /// @param tickSpacing The spacing between usable ticks\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(\n mapping(int16 => uint256) storage self,\n int24 tick,\n int24 tickSpacing,\n bool lte\n ) internal view returns (int24 next, bool initialized) {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = self[wordPos] & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing\n : (compressed - int24(bitPos)) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = self[wordPos] & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing\n : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;\n }\n }\n}\n"
},
"contracts/libraries/Position.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './FixedPoint128.sol';\nimport './LiquidityMath.sol';\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n // info stored for each user's position\n struct Info {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n // the fees owed to the position owner in token0/token1\n uint128 tokensOwed0;\n uint128 tokensOwed1;\n }\n\n /// @notice Returns the Info struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @return position The position info struct of the given owners' position\n function get(\n mapping(bytes32 => Info) storage self,\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (Position.Info storage position) {\n position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))];\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function update(\n Info storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal {\n Info memory _self = self;\n\n uint128 liquidityNext;\n if (liquidityDelta == 0) {\n require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions\n liquidityNext = _self.liquidity;\n } else {\n liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees\n uint128 tokensOwed0 =\n uint128(\n FullMath.mulDiv(\n feeGrowthInside0X128 - _self.feeGrowthInside0LastX128,\n _self.liquidity,\n FixedPoint128.Q128\n )\n );\n uint128 tokensOwed1 =\n uint128(\n FullMath.mulDiv(\n feeGrowthInside1X128 - _self.feeGrowthInside1LastX128,\n _self.liquidity,\n FixedPoint128.Q128\n )\n );\n\n // update the position\n if (liquidityDelta != 0) self.liquidity = liquidityNext;\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n if (tokensOwed0 > 0 || tokensOwed1 > 0) {\n // overflow is acceptable, have to withdraw before you hit type(uint128).max fees\n self.tokensOwed0 += tokensOwed0;\n self.tokensOwed1 += tokensOwed1;\n }\n }\n}\n"
},
"contracts/libraries/Oracle.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\n/// @title Oracle\n/// @notice Provides price and liquidity data useful for a wide variety of system designs\n/// @dev Instances of stored oracle data, \"observations\", are collected in the oracle array\n/// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the\n/// maximum length of the oracle array. New slots will be added when the array is fully populated.\n/// Observations are overwritten when the full length of the oracle array is populated.\n/// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()\nlibrary Oracle {\n struct Observation {\n // the block timestamp of the observation\n uint32 blockTimestamp;\n // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized\n int56 tickCumulative;\n // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized\n uint160 secondsPerLiquidityCumulativeX128;\n // whether or not the observation is initialized\n bool initialized;\n }\n\n /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values\n /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows\n /// @param last The specified observation to be transformed\n /// @param blockTimestamp The timestamp of the new observation\n /// @param tick The active tick at the time of the new observation\n /// @param liquidity The total in-range liquidity at the time of the new observation\n /// @return Observation The newly populated observation\n function transform(\n Observation memory last,\n uint32 blockTimestamp,\n int24 tick,\n uint128 liquidity\n ) private pure returns (Observation memory) {\n uint32 delta = blockTimestamp - last.blockTimestamp;\n return\n Observation({\n blockTimestamp: blockTimestamp,\n tickCumulative: last.tickCumulative + int56(tick) * delta,\n secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +\n ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),\n initialized: true\n });\n }\n\n /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array\n /// @param self The stored oracle array\n /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32\n /// @return cardinality The number of populated elements in the oracle array\n /// @return cardinalityNext The new length of the oracle array, independent of population\n function initialize(Observation[65535] storage self, uint32 time)\n internal\n returns (uint16 cardinality, uint16 cardinalityNext)\n {\n self[0] = Observation({\n blockTimestamp: time,\n tickCumulative: 0,\n secondsPerLiquidityCumulativeX128: 0,\n initialized: true\n });\n return (1, 1);\n }\n\n /// @notice Writes an oracle observation to the array\n /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.\n /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality\n /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.\n /// @param self The stored oracle array\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param blockTimestamp The timestamp of the new observation\n /// @param tick The active tick at the time of the new observation\n /// @param liquidity The total in-range liquidity at the time of the new observation\n /// @param cardinality The number of populated elements in the oracle array\n /// @param cardinalityNext The new length of the oracle array, independent of population\n /// @return indexUpdated The new index of the most recently written element in the oracle array\n /// @return cardinalityUpdated The new cardinality of the oracle array\n function write(\n Observation[65535] storage self,\n uint16 index,\n uint32 blockTimestamp,\n int24 tick,\n uint128 liquidity,\n uint16 cardinality,\n uint16 cardinalityNext\n ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {\n Observation memory last = self[index];\n\n // early return if we've already written an observation this block\n if (last.blockTimestamp == blockTimestamp) return (index, cardinality);\n\n // if the conditions are right, we can bump the cardinality\n if (cardinalityNext > cardinality && index == (cardinality - 1)) {\n cardinalityUpdated = cardinalityNext;\n } else {\n cardinalityUpdated = cardinality;\n }\n\n indexUpdated = (index + 1) % cardinalityUpdated;\n self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);\n }\n\n /// @notice Prepares the oracle array to store up to `next` observations\n /// @param self The stored oracle array\n /// @param current The current next cardinality of the oracle array\n /// @param next The proposed next cardinality which will be populated in the oracle array\n /// @return next The next cardinality which will be populated in the oracle array\n function grow(\n Observation[65535] storage self,\n uint16 current,\n uint16 next\n ) internal returns (uint16) {\n require(current > 0, 'I');\n // no-op if the passed next value isn't greater than the current next value\n if (next <= current) return current;\n // store in each slot to prevent fresh SSTOREs in swaps\n // this data will not be used because the initialized boolean is still false\n for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;\n return next;\n }\n\n /// @notice comparator for 32-bit timestamps\n /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time\n /// @param time A timestamp truncated to 32 bits\n /// @param a A comparison timestamp from which to determine the relative position of `time`\n /// @param b From which to determine the relative position of `time`\n /// @return bool Whether `a` is chronologically <= `b`\n function lte(\n uint32 time,\n uint32 a,\n uint32 b\n ) private pure returns (bool) {\n // if there hasn't been overflow, no need to adjust\n if (a <= time && b <= time) return a <= b;\n\n uint256 aAdjusted = a > time ? a : a + 2**32;\n uint256 bAdjusted = b > time ? b : b + 2**32;\n\n return aAdjusted <= bAdjusted;\n }\n\n /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.\n /// The result may be the same observation, or adjacent observations.\n /// @dev The answer must be contained in the array, used when the target is located within the stored observation\n /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param target The timestamp at which the reserved observation should be for\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param cardinality The number of populated elements in the oracle array\n /// @return beforeOrAt The observation recorded before, or at, the target\n /// @return atOrAfter The observation recorded at, or after, the target\n function binarySearch(\n Observation[65535] storage self,\n uint32 time,\n uint32 target,\n uint16 index,\n uint16 cardinality\n ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n uint256 l = (index + 1) % cardinality; // oldest observation\n uint256 r = l + cardinality - 1; // newest observation\n uint256 i;\n while (true) {\n i = (l + r) / 2;\n\n beforeOrAt = self[i % cardinality];\n\n // we've landed on an uninitialized tick, keep searching higher (more recently)\n if (!beforeOrAt.initialized) {\n l = i + 1;\n continue;\n }\n\n atOrAfter = self[(i + 1) % cardinality];\n\n bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);\n\n // check if we've found the answer!\n if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;\n\n if (!targetAtOrAfter) r = i - 1;\n else l = i + 1;\n }\n }\n\n /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied\n /// @dev Assumes there is at least 1 initialized observation.\n /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param target The timestamp at which the reserved observation should be for\n /// @param tick The active tick at the time of the returned or simulated observation\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The total pool liquidity at the time of the call\n /// @param cardinality The number of populated elements in the oracle array\n /// @return beforeOrAt The observation which occurred at, or before, the given timestamp\n /// @return atOrAfter The observation which occurred at, or after, the given timestamp\n function getSurroundingObservations(\n Observation[65535] storage self,\n uint32 time,\n uint32 target,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n // optimistically set before to the newest observation\n beforeOrAt = self[index];\n\n // if the target is chronologically at or after the newest observation, we can early return\n if (lte(time, beforeOrAt.blockTimestamp, target)) {\n if (beforeOrAt.blockTimestamp == target) {\n // if newest observation equals target, we're in the same block, so we can ignore atOrAfter\n return (beforeOrAt, atOrAfter);\n } else {\n // otherwise, we need to transform\n return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));\n }\n }\n\n // now, set before to the oldest observation\n beforeOrAt = self[(index + 1) % cardinality];\n if (!beforeOrAt.initialized) beforeOrAt = self[0];\n\n // ensure that the target is chronologically at or after the oldest observation\n require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');\n\n // if we've reached this point, we have to binary search\n return binarySearch(self, time, target, index, cardinality);\n }\n\n /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.\n /// 0 may be passed as `secondsAgo' to return the current cumulative values.\n /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values\n /// at exactly the timestamp between the two observations.\n /// @param self The stored oracle array\n /// @param time The current block timestamp\n /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation\n /// @param tick The current tick\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The current in-range pool liquidity\n /// @param cardinality The number of populated elements in the oracle array\n /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`\n /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`\n function observeSingle(\n Observation[65535] storage self,\n uint32 time,\n uint32 secondsAgo,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {\n if (secondsAgo == 0) {\n Observation memory last = self[index];\n if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity);\n return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);\n }\n\n uint32 target = time - secondsAgo;\n\n (Observation memory beforeOrAt, Observation memory atOrAfter) =\n getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);\n\n if (target == beforeOrAt.blockTimestamp) {\n // we're at the left boundary\n return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);\n } else if (target == atOrAfter.blockTimestamp) {\n // we're at the right boundary\n return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);\n } else {\n // we're in the middle\n uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;\n uint32 targetDelta = target - beforeOrAt.blockTimestamp;\n return (\n beforeOrAt.tickCumulative +\n ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *\n targetDelta,\n beforeOrAt.secondsPerLiquidityCumulativeX128 +\n uint160(\n (uint256(\n atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128\n ) * targetDelta) / observationTimeDelta\n )\n );\n }\n }\n\n /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`\n /// @dev Reverts if `secondsAgos` > oldest observation\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation\n /// @param tick The current tick\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The current in-range pool liquidity\n /// @param cardinality The number of populated elements in the oracle array\n /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`\n /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`\n function observe(\n Observation[65535] storage self,\n uint32 time,\n uint32[] memory secondsAgos,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {\n require(cardinality > 0, 'I');\n\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle(\n self,\n time,\n secondsAgos[i],\n tick,\n index,\n liquidity,\n cardinality\n );\n }\n }\n}\n"
},
"contracts/libraries/FullMath.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n function mulDiv(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n // 512-bit multiply [prod1 prod0] = a * b\n // Compute the product mod 2**256 and mod 2**256 - 1\n // then use the Chinese Remainder Theorem to reconstruct\n // the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2**256 + prod0\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(a, b, not(0))\n prod0 := mul(a, b)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n require(denominator > 0);\n assembly {\n result := div(prod0, denominator)\n }\n return result;\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0]\n // Compute remainder using mulmod\n uint256 remainder;\n assembly {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly {\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator\n // Compute largest power of two divisor of denominator.\n // Always >= 1.\n uint256 twos = -denominator & denominator;\n // Divide denominator by power of two\n assembly {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly {\n prod0 := div(prod0, twos)\n }\n // Shift in bits from prod1 into prod0. For this we need\n // to flip `twos` such that it is 2**256 / twos.\n // If twos is zero, then it becomes one\n assembly {\n twos := add(div(sub(0, twos), twos), 1)\n }\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2**256\n // Now that denominator is an odd number, it has an inverse\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n // Compute the inverse by starting with a seed that is correct\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\n uint256 inv = (3 * denominator) ^ 2;\n // Now use Newton-Raphson iteration to improve the precision.\n // Thanks to Hensel's lifting lemma, this also works in modular\n // arithmetic, doubling the correct bits in each step.\n inv *= 2 - denominator * inv; // inverse mod 2**8\n inv *= 2 - denominator * inv; // inverse mod 2**16\n inv *= 2 - denominator * inv; // inverse mod 2**32\n inv *= 2 - denominator * inv; // inverse mod 2**64\n inv *= 2 - denominator * inv; // inverse mod 2**128\n inv *= 2 - denominator * inv; // inverse mod 2**256\n\n // Because the division is now exact we can divide by multiplying\n // with the modular inverse of denominator. This will give us the\n // correct result modulo 2**256. Since the precoditions guarantee\n // that the outcome is less than 2**256, this is the final result.\n // We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inv;\n return result;\n }\n\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n function mulDivRoundingUp(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) > 0) {\n require(result < type(uint256).max);\n result++;\n }\n }\n}\n"
},
"contracts/libraries/FixedPoint128.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n"
},
"contracts/libraries/TransferHelper.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../interfaces/IERC20Minimal.sol';\n\n/// @title TransferHelper\n/// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false\nlibrary TransferHelper {\n /// @notice Transfers tokens from msg.sender to a recipient\n /// @dev Calls transfer on token contract, errors with TF if transfer fails\n /// @param token The contract address of the token which will be transferred\n /// @param to The recipient of the transfer\n /// @param value The value of the transfer\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) =\n token.call(abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');\n }\n}\n"
},
"contracts/libraries/TickMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n int24 internal constant MIN_TICK = -887272;\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n int24 internal constant MAX_TICK = -MIN_TICK;\n\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\n /// @dev Throws if |tick| > max tick\n /// @param tick The input tick for the above formula\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n /// at the given tick\n function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n require(absTick <= uint256(MAX_TICK), 'T');\n\n uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n if (tick > 0) ratio = type(uint256).max / ratio;\n\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n }\n\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n /// ever return.\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n // second inequality must be < because the price can never reach the price at the max tick\n require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');\n uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n uint256 r = ratio;\n uint256 msb = 0;\n\n assembly {\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(5, gt(r, 0xFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(4, gt(r, 0xFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(3, gt(r, 0xFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(2, gt(r, 0xF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(1, gt(r, 0x3))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := gt(r, 0x1)\n msb := or(msb, f)\n }\n\n if (msb >= 128) r = ratio >> (msb - 127);\n else r = ratio << (127 - msb);\n\n int256 log_2 = (int256(msb) - 128) << 64;\n\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(63, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(62, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(61, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(60, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(59, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(58, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(57, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(56, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(55, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(54, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(53, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(52, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(51, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(50, f))\n }\n\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n }\n}\n"
},
"contracts/libraries/LiquidityMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}\n"
},
"contracts/libraries/SqrtPriceMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}\n"
},
"contracts/libraries/SwapMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\n }\n }\n}\n"
},
"contracts/interfaces/IUniswapV3PoolDeployer.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title An interface for a contract that is capable of deploying Uniswap V3 Pools\n/// @notice A contract that constructs a pool must implement this to pass arguments to the pool\n/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash\n/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain\ninterface IUniswapV3PoolDeployer {\n /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.\n /// @dev Called by the pool constructor to fetch the parameters of the pool\n /// Returns factory The factory address\n /// Returns token0 The first token of the pool by address sort order\n /// Returns token1 The second token of the pool by address sort order\n /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// Returns tickSpacing The minimum number of ticks between initialized ticks\n function parameters()\n external\n view\n returns (\n address factory,\n address token0,\n address token1,\n uint24 fee,\n int24 tickSpacing\n );\n}\n"
},
"contracts/interfaces/IUniswapV3Factory.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n /// @notice Emitted when the owner of the factory is changed\n /// @param oldOwner The owner before the owner was changed\n /// @param newOwner The owner after the owner was changed\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n /// @notice Emitted when a pool is created\n /// @param token0 The first token of the pool by address sort order\n /// @param token1 The second token of the pool by address sort order\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks\n /// @param pool The address of the created pool\n event PoolCreated(\n address indexed token0,\n address indexed token1,\n uint24 indexed fee,\n int24 tickSpacing,\n address pool\n );\n\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n /// @param fee The enabled fee, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n /// @notice Returns the current owner of the factory\n /// @dev Can be changed by the current owner via setOwner\n /// @return The address of the factory owner\n function owner() external view returns (address);\n\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n /// @return The tick spacing\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The pool address\n function getPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external view returns (address pool);\n\n /// @notice Creates a pool for the given two tokens and fee\n /// @param tokenA One of the two tokens in the desired pool\n /// @param tokenB The other of the two tokens in the desired pool\n /// @param fee The desired fee for the pool\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n /// are invalid.\n /// @return pool The address of the newly created pool\n function createPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external returns (address pool);\n\n /// @notice Updates the owner of the factory\n /// @dev Must be called by the current owner\n /// @param _owner The new owner of the factory\n function setOwner(address _owner) external;\n\n /// @notice Enables a fee amount with the given tickSpacing\n /// @dev Fee amounts may never be removed once enabled\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n"
},
"contracts/interfaces/IERC20Minimal.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/interfaces/callback/IUniswapV3MintCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#mint\n/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface\ninterface IUniswapV3MintCallback {\n /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.\n /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity\n /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call\n function uniswapV3MintCallback(\n uint256 amount0Owed,\n uint256 amount1Owed,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/callback/IUniswapV3SwapCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/callback/IUniswapV3FlashCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#flash\n/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface\ninterface IUniswapV3FlashCallback {\n /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.\n /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param fee0 The fee amount in token0 due to the pool by the end of the flash\n /// @param fee1 The fee amount in token1 due to the pool by the end of the flash\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolImmutables.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n /// @return The contract address\n function factory() external view returns (address);\n\n /// @notice The first of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token0() external view returns (address);\n\n /// @notice The second of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token1() external view returns (address);\n\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n /// @return The fee\n function fee() external view returns (uint24);\n\n /// @notice The pool tick spacing\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n /// This value is an int24 to avoid casting even though it is always positive.\n /// @return The tick spacing\n function tickSpacing() external view returns (int24);\n\n /// @notice The maximum amount of position liquidity that can use any tick in the range\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n /// @return The max amount of liquidity per tick\n function maxLiquidityPerTick() external view returns (uint128);\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n /// when accessed externally.\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n /// boundary.\n /// observationIndex The index of the last oracle observation that was written,\n /// observationCardinality The current maximum number of observations stored in the pool,\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n /// feeProtocol The protocol fee for both tokens of the pool.\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n /// unlocked Whether the pool is currently locked to reentrancy\n function slot0()\n external\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n uint16 observationCardinalityNext,\n uint8 feeProtocol,\n bool unlocked\n );\n\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal0X128() external view returns (uint256);\n\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal1X128() external view returns (uint256);\n\n /// @notice The amounts of token0 and token1 that are owed to the protocol\n /// @dev Protocol fees will never exceed uint128 max in either token\n function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n /// @notice The currently in range liquidity available to the pool\n /// @dev This value has no relationship to the total liquidity across all ticks\n function liquidity() external view returns (uint128);\n\n /// @notice Look up information about a specific tick in the pool\n /// @param tick The tick to look up\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n /// tick upper,\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n /// a specific position.\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128,\n int56 tickCumulativeOutside,\n uint160 secondsPerLiquidityOutsideX128,\n uint32 secondsOutside,\n bool initialized\n );\n\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n /// @notice Returns the information about a position by the position's key\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n /// @return _liquidity The amount of liquidity in the position,\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 _liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n\n /// @notice Returns data about a specific observation index\n /// @param index The element of the observations array to fetch\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n /// ago, rather than at a specific index in the array.\n /// @return blockTimestamp The timestamp of the observation,\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n /// Returns initialized whether the observation has been initialized and the values are safe to use\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulativeX128,\n bool initialized\n );\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n /// you must call it with secondsAgos = [3600, 0].\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n /// timestamp\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n /// snapshot is taken and the second snapshot is taken.\n /// @param tickLower The lower tick of the range\n /// @param tickUpper The upper tick of the range\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n /// @return secondsInside The snapshot of seconds per liquidity for the range\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n );\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n /// @notice Sets the initial price for the pool\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n function initialize(uint160 sqrtPriceX96) external;\n\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n /// @param recipient The address for which the liquidity will be created\n /// @param tickLower The lower tick of the position in which to add liquidity\n /// @param tickUpper The upper tick of the position in which to add liquidity\n /// @param amount The amount of liquidity to mint\n /// @param data Any data that should be passed through to the callback\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Collects tokens owed to a position\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n /// @param recipient The address which should receive the fees collected\n /// @param tickLower The lower tick of the position for which to collect fees\n /// @param tickUpper The upper tick of the position for which to collect fees\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n /// @dev Fees must be collected separately via a call to #collect\n /// @param tickLower The lower tick of the position for which to burn liquidity\n /// @param tickUpper The upper tick of the position for which to burn liquidity\n /// @param amount How much liquidity to burn\n /// @return amount0 The amount of token0 sent to the recipient\n /// @return amount1 The amount of token1 sent to the recipient\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Swap token0 for token1, or token1 for token0\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n /// @param recipient The address to receive the output of the swap\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n /// @param data Any data to be passed through to the callback\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n /// @param recipient The address which will receive the token0 and token1 amounts\n /// @param amount0 The amount of token0 to send\n /// @param amount1 The amount of token1 to send\n /// @param data Any data to be passed through to the callback\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n /// the input observationCardinalityNext.\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n /// @notice Set the denominator of the protocol's % share of the fees\n /// @param feeProtocol0 new protocol fee for token0 of the pool\n /// @param feeProtocol1 new protocol fee for token1 of the pool\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n /// @notice Collect the protocol fee accrued to the pool\n /// @param recipient The address to which collected protocol fees should be sent\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n /// @return amount0 The protocol fee collected in token0\n /// @return amount1 The protocol fee collected in token1\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n /// @notice Emitted when liquidity is minted for a given position\n /// @param sender The address that minted the liquidity\n /// @param owner The owner of the position and recipient of any minted liquidity\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity minted to the position range\n /// @param amount0 How much token0 was required for the minted liquidity\n /// @param amount1 How much token1 was required for the minted liquidity\n event Mint(\n address sender,\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when fees are collected by the owner of a position\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n /// @param owner The owner of the position for which fees are collected\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount0 The amount of token0 fees collected\n /// @param amount1 The amount of token1 fees collected\n event Collect(\n address indexed owner,\n address recipient,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount0,\n uint128 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n /// @param owner The owner of the position for which liquidity is removed\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity to remove\n /// @param amount0 The amount of token0 withdrawn\n /// @param amount1 The amount of token1 withdrawn\n event Burn(\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted by the pool for any swaps between token0 and token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the output of the swap\n /// @param amount0 The delta of the token0 balance of the pool\n /// @param amount1 The delta of the token1 balance of the pool\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n /// @param liquidity The liquidity of the pool after the swap\n /// @param tick The log base 1.0001 of price of the pool after the swap\n event Swap(\n address indexed sender,\n address indexed recipient,\n int256 amount0,\n int256 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick\n );\n\n /// @notice Emitted by the pool for any flashes of token0/token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the tokens from flash\n /// @param amount0 The amount of token0 that was flashed\n /// @param amount1 The amount of token1 that was flashed\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n event Flash(\n address indexed sender,\n address indexed recipient,\n uint256 amount0,\n uint256 amount1,\n uint256 paid0,\n uint256 paid1\n );\n\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n /// just before a mint/swap/burn.\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n event IncreaseObservationCardinalityNext(\n uint16 observationCardinalityNextOld,\n uint16 observationCardinalityNextNew\n );\n\n /// @notice Emitted when the protocol fee is changed by the pool\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\n /// @param feeProtocol0New The updated value of the token0 protocol fee\n /// @param feeProtocol1New The updated value of the token1 protocol fee\n event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n /// @param sender The address that collects the protocol fees\n /// @param recipient The address that receives the collected protocol fees\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\n event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
},
"contracts/libraries/BitMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\n }\n}\n"
},
"contracts/libraries/UnsafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}\n"
},
"contracts/libraries/FixedPoint96.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n uint8 internal constant RESOLUTION = 96;\n uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 800
},
"metadata": {
"bytecodeHash": "none"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,499,943 |
6ac9f942140ac0b8bd4d5b8da19fdb400a1869d596f4a287b2d27e3bab33555f
|
916b8e54551b88f69cca32afd98d5ce3fecadf1b6982de22a983acb140e57cfc
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
f312c1b5182fef744d3906f1205c47eaec390098
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,499,945 |
3ab35dc06d0e90997b21cad50f6a287df318c55afcce34dd2370b581f780157f
|
955952f88692b03409bce388eb3223d04fd80871b299e331e37ca41c751d72f2
|
4cc0abfa6ab142bc850df354c24f472ebcbe7c7e
|
4cc0abfa6ab142bc850df354c24f472ebcbe7c7e
|
e94953e9231bf93ced466bdbbf445604696cbf9c
|
60806040525f600560146101000a81548160ff0219169083151502179055503480156200002a575f80fd5b50336040518060400160405280600b81526020017f47696761627974652041490000000000000000000000000000000000000000008152506040518060400160405280600281526020017f47420000000000000000000000000000000000000000000000000000000000008152508160039081620000a9919062000765565b508060049081620000bb919062000765565b5050505f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff160362000131575f6040517f1e4fbdf70000000000000000000000000000000000000000000000000000000081526004016200012891906200088c565b60405180910390fd5b62000142816200018860201b60201c565b506200018233620001586200024b60201b60201c565b600a62000166919062000a30565b6298968062000176919062000a80565b6200025360201b60201c565b62000b6b565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508160055f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35050565b5f6012905090565b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603620002c6575f6040517fec442f05000000000000000000000000000000000000000000000000000000008152600401620002bd91906200088c565b60405180910390fd5b620002d95f8383620002dd60201b60201c565b5050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160362000331578060025f82825462000324919062000aca565b9250508190555062000402565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905081811015620003bd578381836040517fe450d38c000000000000000000000000000000000000000000000000000000008152600401620003b49392919062000b15565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036200044b578060025f828254039250508190555062000495565b805f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051620004f4919062000b50565b60405180910390a3505050565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806200057d57607f821691505b60208210810362000593576200059262000538565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f60088302620005f77fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82620005ba565b620006038683620005ba565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f6200064d6200064762000641846200061b565b62000624565b6200061b565b9050919050565b5f819050919050565b62000668836200062d565b62000680620006778262000654565b848454620005c6565b825550505050565b5f90565b6200069662000688565b620006a38184846200065d565b505050565b5b81811015620006ca57620006be5f826200068c565b600181019050620006a9565b5050565b601f8211156200071957620006e38162000599565b620006ee84620005ab565b81016020851015620006fe578190505b620007166200070d85620005ab565b830182620006a8565b50505b505050565b5f82821c905092915050565b5f6200073b5f19846008026200071e565b1980831691505092915050565b5f6200075583836200072a565b9150826002028217905092915050565b620007708262000501565b67ffffffffffffffff8111156200078c576200078b6200050b565b5b62000798825462000565565b620007a5828285620006ce565b5f60209050601f831160018114620007db575f8415620007c6578287015190505b620007d2858262000748565b86555062000841565b601f198416620007eb8662000599565b5f5b828110156200081457848901518255600182019150602085019450602081019050620007ed565b8683101562000834578489015162000830601f8916826200072a565b8355505b6001600288020188555050505b505050505050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f620008748262000849565b9050919050565b620008868162000868565b82525050565b5f602082019050620008a15f8301846200087b565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b60018511156200093157808604811115620009095762000908620008a7565b5b6001851615620009195780820291505b80810290506200092985620008d4565b9450620008e9565b94509492505050565b5f826200094b576001905062000a1d565b816200095a575f905062000a1d565b81600181146200097357600281146200097e57620009b4565b600191505062000a1d565b60ff841115620009935762000992620008a7565b5b8360020a915084821115620009ad57620009ac620008a7565b5b5062000a1d565b5060208310610133831016604e8410600b8410161715620009ee5782820a905083811115620009e857620009e7620008a7565b5b62000a1d565b620009fd8484846001620008e0565b9250905081840481111562000a175762000a16620008a7565b5b81810290505b9392505050565b5f60ff82169050919050565b5f62000a3c826200061b565b915062000a498362000a24565b925062000a787fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff84846200093a565b905092915050565b5f62000a8c826200061b565b915062000a99836200061b565b925082820262000aa9816200061b565b9150828204841483151762000ac35762000ac2620008a7565b5b5092915050565b5f62000ad6826200061b565b915062000ae3836200061b565b925082820190508082111562000afe5762000afd620008a7565b5b92915050565b62000b0f816200061b565b82525050565b5f60608201905062000b2a5f8301866200087b565b62000b39602083018562000b04565b62000b48604083018462000b04565b949350505050565b5f60208201905062000b655f83018462000b04565b92915050565b6113c88062000b795f395ff3fe608060405234801561000f575f80fd5b50600436106100e8575f3560e01c806370a082311161008a57806395d89b411161006457806395d89b4114610238578063a9059cbb14610256578063dd62ed3e14610286578063f2fde38b146102b6576100e8565b806370a08231146101e0578063715018a6146102105780638da5cb5b1461021a576100e8565b806318160ddd116100c657806318160ddd1461015857806323b872dd1461017657806326560be7146101a6578063313ce567146101c2576100e8565b8063064a59d0146100ec57806306fdde031461010a578063095ea7b314610128575b5f80fd5b6100f46102d2565b6040516101019190610f14565b60405180910390f35b6101126102e8565b60405161011f9190610fb7565b60405180910390f35b610142600480360381019061013d9190611068565b610378565b60405161014f9190610f14565b60405180910390f35b61016061039a565b60405161016d91906110b5565b60405180910390f35b610190600480360381019061018b91906110ce565b6103a3565b60405161019d9190610f14565b60405180910390f35b6101c060048036038101906101bb9190611148565b6104be565b005b6101ca6104e3565b6040516101d7919061118e565b60405180910390f35b6101fa60048036038101906101f591906111a7565b6104eb565b60405161020791906110b5565b60405180910390f35b610218610530565b005b610222610543565b60405161022f91906111e1565b60405180910390f35b61024061056b565b60405161024d9190610fb7565b60405180910390f35b610270600480360381019061026b9190611068565b6105fb565b60405161027d9190610f14565b60405180910390f35b6102a0600480360381019061029b91906111fa565b6106d7565b6040516102ad91906110b5565b60405180910390f35b6102d060048036038101906102cb91906111a7565b610759565b005b5f600560149054906101000a900460ff16905090565b6060600380546102f790611265565b80601f016020809104026020016040519081016040528092919081815260200182805461032390611265565b801561036e5780601f106103455761010080835404028352916020019161036e565b820191905f5260205f20905b81548152906001019060200180831161035157829003601f168201915b5050505050905090565b5f806103826107dd565b905061038f8185856107e4565b600191505092915050565b5f600254905090565b5f600560149054906101000a900460ff16806103f157506103c2610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b8061042e57506103ff610543565b73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16145b8061046b575061043c610543565b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b6104aa576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104a1906112df565b60405180910390fd5b6104b58484846107f6565b90509392505050565b6104c6610824565b80600560146101000a81548160ff02191690831515021790555050565b5f6012905090565b5f805f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b610538610824565b6105415f6108ab565b565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b60606004805461057a90611265565b80601f01602080910402602001604051908101604052809291908181526020018280546105a690611265565b80156105f15780601f106105c8576101008083540402835291602001916105f1565b820191905f5260205f20905b8154815290600101906020018083116105d457829003601f168201915b5050505050905090565b5f600560149054906101000a900460ff1680610649575061061a610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b806106865750610657610543565b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b6106c5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106bc906112df565b60405180910390fd5b6106cf838361096e565b905092915050565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b610761610824565b5f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16036107d1575f6040517f1e4fbdf70000000000000000000000000000000000000000000000000000000081526004016107c891906111e1565b60405180910390fd5b6107da816108ab565b50565b5f33905090565b6107f18383836001610990565b505050565b5f806108006107dd565b905061080d858285610b5f565b610818858585610bf1565b60019150509392505050565b61082c6107dd565b73ffffffffffffffffffffffffffffffffffffffff1661084a610543565b73ffffffffffffffffffffffffffffffffffffffff16146108a95761086d6107dd565b6040517f118cdaa70000000000000000000000000000000000000000000000000000000081526004016108a091906111e1565b60405180910390fd5b565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508160055f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35050565b5f806109786107dd565b9050610985818585610bf1565b600191505092915050565b5f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1603610a00575f6040517fe602df050000000000000000000000000000000000000000000000000000000081526004016109f791906111e1565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610a70575f6040517f94280d62000000000000000000000000000000000000000000000000000000008152600401610a6791906111e1565b60405180910390fd5b8160015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508015610b59578273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051610b5091906110b5565b60405180910390a35b50505050565b5f610b6a84846106d7565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114610beb5781811015610bdc578281836040517ffb8f41b2000000000000000000000000000000000000000000000000000000008152600401610bd3939291906112fd565b60405180910390fd5b610bea84848484035f610990565b5b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610c61575f6040517f96c6fd1e000000000000000000000000000000000000000000000000000000008152600401610c5891906111e1565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610cd1575f6040517fec442f05000000000000000000000000000000000000000000000000000000008152600401610cc891906111e1565b60405180910390fd5b610cdc838383610ce1565b505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610d31578060025f828254610d25919061135f565b92505081905550610dff565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905081811015610dba578381836040517fe450d38c000000000000000000000000000000000000000000000000000000008152600401610db1939291906112fd565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610e46578060025f8282540392505081905550610e90565b805f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610eed91906110b5565b60405180910390a3505050565b5f8115159050919050565b610f0e81610efa565b82525050565b5f602082019050610f275f830184610f05565b92915050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015610f64578082015181840152602081019050610f49565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610f8982610f2d565b610f938185610f37565b9350610fa3818560208601610f47565b610fac81610f6f565b840191505092915050565b5f6020820190508181035f830152610fcf8184610f7f565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61100482610fdb565b9050919050565b61101481610ffa565b811461101e575f80fd5b50565b5f8135905061102f8161100b565b92915050565b5f819050919050565b61104781611035565b8114611051575f80fd5b50565b5f813590506110628161103e565b92915050565b5f806040838503121561107e5761107d610fd7565b5b5f61108b85828601611021565b925050602061109c85828601611054565b9150509250929050565b6110af81611035565b82525050565b5f6020820190506110c85f8301846110a6565b92915050565b5f805f606084860312156110e5576110e4610fd7565b5b5f6110f286828701611021565b935050602061110386828701611021565b925050604061111486828701611054565b9150509250925092565b61112781610efa565b8114611131575f80fd5b50565b5f813590506111428161111e565b92915050565b5f6020828403121561115d5761115c610fd7565b5b5f61116a84828501611134565b91505092915050565b5f60ff82169050919050565b61118881611173565b82525050565b5f6020820190506111a15f83018461117f565b92915050565b5f602082840312156111bc576111bb610fd7565b5b5f6111c984828501611021565b91505092915050565b6111db81610ffa565b82525050565b5f6020820190506111f45f8301846111d2565b92915050565b5f80604083850312156112105761120f610fd7565b5b5f61121d85828601611021565b925050602061122e85828601611021565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f600282049050600182168061127c57607f821691505b60208210810361128f5761128e611238565b5b50919050565b7f5472616e736665727320617265207061757365640000000000000000000000005f82015250565b5f6112c9601483610f37565b91506112d482611295565b602082019050919050565b5f6020820190508181035f8301526112f6816112bd565b9050919050565b5f6060820190506113105f8301866111d2565b61131d60208301856110a6565b61132a60408301846110a6565b949350505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61136982611035565b915061137483611035565b925082820190508082111561138c5761138b611332565b5b9291505056fea264697066735822122087dadc47a9b8550117f10f431cd906fb1fdb3a002a8160cacf94d0c1937ae54364736f6c63430008180033
|
608060405234801561000f575f80fd5b50600436106100e8575f3560e01c806370a082311161008a57806395d89b411161006457806395d89b4114610238578063a9059cbb14610256578063dd62ed3e14610286578063f2fde38b146102b6576100e8565b806370a08231146101e0578063715018a6146102105780638da5cb5b1461021a576100e8565b806318160ddd116100c657806318160ddd1461015857806323b872dd1461017657806326560be7146101a6578063313ce567146101c2576100e8565b8063064a59d0146100ec57806306fdde031461010a578063095ea7b314610128575b5f80fd5b6100f46102d2565b6040516101019190610f14565b60405180910390f35b6101126102e8565b60405161011f9190610fb7565b60405180910390f35b610142600480360381019061013d9190611068565b610378565b60405161014f9190610f14565b60405180910390f35b61016061039a565b60405161016d91906110b5565b60405180910390f35b610190600480360381019061018b91906110ce565b6103a3565b60405161019d9190610f14565b60405180910390f35b6101c060048036038101906101bb9190611148565b6104be565b005b6101ca6104e3565b6040516101d7919061118e565b60405180910390f35b6101fa60048036038101906101f591906111a7565b6104eb565b60405161020791906110b5565b60405180910390f35b610218610530565b005b610222610543565b60405161022f91906111e1565b60405180910390f35b61024061056b565b60405161024d9190610fb7565b60405180910390f35b610270600480360381019061026b9190611068565b6105fb565b60405161027d9190610f14565b60405180910390f35b6102a0600480360381019061029b91906111fa565b6106d7565b6040516102ad91906110b5565b60405180910390f35b6102d060048036038101906102cb91906111a7565b610759565b005b5f600560149054906101000a900460ff16905090565b6060600380546102f790611265565b80601f016020809104026020016040519081016040528092919081815260200182805461032390611265565b801561036e5780601f106103455761010080835404028352916020019161036e565b820191905f5260205f20905b81548152906001019060200180831161035157829003601f168201915b5050505050905090565b5f806103826107dd565b905061038f8185856107e4565b600191505092915050565b5f600254905090565b5f600560149054906101000a900460ff16806103f157506103c2610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b8061042e57506103ff610543565b73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16145b8061046b575061043c610543565b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b6104aa576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104a1906112df565b60405180910390fd5b6104b58484846107f6565b90509392505050565b6104c6610824565b80600560146101000a81548160ff02191690831515021790555050565b5f6012905090565b5f805f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b610538610824565b6105415f6108ab565b565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b60606004805461057a90611265565b80601f01602080910402602001604051908101604052809291908181526020018280546105a690611265565b80156105f15780601f106105c8576101008083540402835291602001916105f1565b820191905f5260205f20905b8154815290600101906020018083116105d457829003601f168201915b5050505050905090565b5f600560149054906101000a900460ff1680610649575061061a610543565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b806106865750610657610543565b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b6106c5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106bc906112df565b60405180910390fd5b6106cf838361096e565b905092915050565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b610761610824565b5f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16036107d1575f6040517f1e4fbdf70000000000000000000000000000000000000000000000000000000081526004016107c891906111e1565b60405180910390fd5b6107da816108ab565b50565b5f33905090565b6107f18383836001610990565b505050565b5f806108006107dd565b905061080d858285610b5f565b610818858585610bf1565b60019150509392505050565b61082c6107dd565b73ffffffffffffffffffffffffffffffffffffffff1661084a610543565b73ffffffffffffffffffffffffffffffffffffffff16146108a95761086d6107dd565b6040517f118cdaa70000000000000000000000000000000000000000000000000000000081526004016108a091906111e1565b60405180910390fd5b565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508160055f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35050565b5f806109786107dd565b9050610985818585610bf1565b600191505092915050565b5f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1603610a00575f6040517fe602df050000000000000000000000000000000000000000000000000000000081526004016109f791906111e1565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610a70575f6040517f94280d62000000000000000000000000000000000000000000000000000000008152600401610a6791906111e1565b60405180910390fd5b8160015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508015610b59578273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051610b5091906110b5565b60405180910390a35b50505050565b5f610b6a84846106d7565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114610beb5781811015610bdc578281836040517ffb8f41b2000000000000000000000000000000000000000000000000000000008152600401610bd3939291906112fd565b60405180910390fd5b610bea84848484035f610990565b5b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610c61575f6040517f96c6fd1e000000000000000000000000000000000000000000000000000000008152600401610c5891906111e1565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610cd1575f6040517fec442f05000000000000000000000000000000000000000000000000000000008152600401610cc891906111e1565b60405180910390fd5b610cdc838383610ce1565b505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610d31578060025f828254610d25919061135f565b92505081905550610dff565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905081811015610dba578381836040517fe450d38c000000000000000000000000000000000000000000000000000000008152600401610db1939291906112fd565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610e46578060025f8282540392505081905550610e90565b805f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610eed91906110b5565b60405180910390a3505050565b5f8115159050919050565b610f0e81610efa565b82525050565b5f602082019050610f275f830184610f05565b92915050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015610f64578082015181840152602081019050610f49565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610f8982610f2d565b610f938185610f37565b9350610fa3818560208601610f47565b610fac81610f6f565b840191505092915050565b5f6020820190508181035f830152610fcf8184610f7f565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61100482610fdb565b9050919050565b61101481610ffa565b811461101e575f80fd5b50565b5f8135905061102f8161100b565b92915050565b5f819050919050565b61104781611035565b8114611051575f80fd5b50565b5f813590506110628161103e565b92915050565b5f806040838503121561107e5761107d610fd7565b5b5f61108b85828601611021565b925050602061109c85828601611054565b9150509250929050565b6110af81611035565b82525050565b5f6020820190506110c85f8301846110a6565b92915050565b5f805f606084860312156110e5576110e4610fd7565b5b5f6110f286828701611021565b935050602061110386828701611021565b925050604061111486828701611054565b9150509250925092565b61112781610efa565b8114611131575f80fd5b50565b5f813590506111428161111e565b92915050565b5f6020828403121561115d5761115c610fd7565b5b5f61116a84828501611134565b91505092915050565b5f60ff82169050919050565b61118881611173565b82525050565b5f6020820190506111a15f83018461117f565b92915050565b5f602082840312156111bc576111bb610fd7565b5b5f6111c984828501611021565b91505092915050565b6111db81610ffa565b82525050565b5f6020820190506111f45f8301846111d2565b92915050565b5f80604083850312156112105761120f610fd7565b5b5f61121d85828601611021565b925050602061122e85828601611021565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f600282049050600182168061127c57607f821691505b60208210810361128f5761128e611238565b5b50919050565b7f5472616e736665727320617265207061757365640000000000000000000000005f82015250565b5f6112c9601483610f37565b91506112d482611295565b602082019050919050565b5f6020820190508181035f8301526112f6816112bd565b9050919050565b5f6060820190506113105f8301866111d2565b61131d60208301856110a6565b61132a60408301846110a6565b949350505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61136982611035565b915061137483611035565b925082820190508082111561138c5761138b611332565b5b9291505056fea264697066735822122087dadc47a9b8550117f10f431cd906fb1fdb3a002a8160cacf94d0c1937ae54364736f6c63430008180033
|
// SPDX-License-Identifier: MIT
/**
Gigabyte AI Community Token
The revolutionary decentralized L2 focused on AI enhanced trading and arbitrage
Ticker: $GB
Website: https://GigabyteAI.live
Come check out our telegram @ https://t.me/GigaByteAiPortal
Or follow us on Twitter / X @ https://twitter.com/GigabyteAI
**/
// File: @openzeppelin/contracts/interfaces/draft-IERC6093.sol
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
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);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
/**
* @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}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* 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.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* 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 returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual 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 default value returned by this function, unless
* it's 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 returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` 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.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// File: contracts/Gigabyte.sol
/**
Gigabyte AI Community Token
The revolutionary decentralized L2 focused on AI enhanced trading and arbitrage
Ticker: $GB
Website: https://GigabyteAI.live
Come check out our telegram @ https://t.me/GigaByteAiPortal
Or follow us on Twitter / X @ https://twitter.com/GigabyteAI
**/
pragma solidity ^0.8.20;
contract GigabyteAI is ERC20, Ownable {
bool private enableTrading = false;
constructor()
ERC20("Gigabyte AI", "GB")
Ownable(msg.sender)
{
_mint(msg.sender, 10000000 * 10 ** decimals());
}
function toggleTrading(bool enable) external onlyOwner {
enableTrading = enable;
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(enableTrading || msg.sender == owner() || recipient == owner(), "Transfers are paused");
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
require(enableTrading || msg.sender == owner() || sender == owner() || recipient == owner(), "Transfers are paused");
return super.transferFrom(sender, recipient, amount);
}
function isTradingEnabled() external view returns (bool) {
return enableTrading;
}
}
|
1 | 19,499,952 |
85ea8cede469a7391214ab8240a395822bb5a73c1325aee6e02d9b20b3a4bf39
|
1ca322b5f295c5c20429cdb2e6e1b41bb3c6dd344e9e72ad2d317c21ef228b30
|
289e02c15d2777def0569641acd811febf55677a
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
3488dee47c400a4bf7416e6ac9b4e290378b39c6
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,499,952 |
85ea8cede469a7391214ab8240a395822bb5a73c1325aee6e02d9b20b3a4bf39
|
48a09ed9955c72ed9faff06f4a77608a13bac9255e6cafceb4954e04d6311a3c
|
49357ba0ef3a8dac25903472eee45c41221d4f9a
|
12715a66773bd9c54534a01abf01d05f6b4bd35e
|
4e28cfcaade932863f2efb68d37a48dbe7295619
|
7f602036038060203d373d3d3d923d343d355af13d82803e903d91601e57fd5bf33d5260203df3
|
602036038060203d373d3d3d923d343d355af13d82803e903d91601e57fd5bf3
| |
1 | 19,499,955 |
295ee51746c98f967deeb39d18ead295c8ec44d2828b6f4b17ed8f1e33892caa
|
863c2ea8aeb279309d207de19d4f495ce2ba5f36c5f4359a7f4726ad8f6bafea
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
e4aba5aa32f6ba69be73df50d979a2d6bca28d93
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,499,959 |
1bdc276ffc1391c68b67792dc4f97cc5d57b15b96ff769835fe159a33cc90b23
|
5651fbf3769902308658943d9b5b3bcca23f4df8802e0c8ead4b88223dbbf6bc
|
a9a0b8a5e1adca0caccc63a168f053cd3be30808
|
01cd62ed13d0b666e2a10d13879a763dfd1dab99
|
5fbbcc773042ec9e4dd7d69f006d6b6f202ca2a6
|
3d602d80600a3d3981f3363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,959 |
1bdc276ffc1391c68b67792dc4f97cc5d57b15b96ff769835fe159a33cc90b23
|
17c35324792c18a0ef8a951d8889dda4e59878a3873581a42c8e3062960d2b67
|
8dbee8f3917049bc30fef01924a7ac79d16cf2b9
|
c1dcb196ba862b337aa23eda1cb9503c0801b955
|
da5eabcfc41d4e04b029f5e0153ed18279f01116
|
608060405234801561001057600080fd5b5060405161028f38038061028f83398101604081905261002f91610191565b6000336001600160a01b031663112e335c6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561006c57600080fd5b505af1158015610080573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100a49190610250565b6001600160a01b0316836040516100bb9190610272565b600060405180830381855af49150503d80600081146100f6576040519150601f19603f3d011682016040523d82523d6000602084013e6100fb565b606091505b5050905080610111576040513d806000833e8082fd5b6001600160a01b038216610123573391505b816001600160a01b0316ff5b634e487b7160e01b600052604160045260246000fd5b60005b83811015610160578181015183820152602001610148565b8381111561016f576000848401525b50505050565b80516001600160a01b038116811461018c57600080fd5b919050565b600080604083850312156101a457600080fd5b82516001600160401b03808211156101bb57600080fd5b818501915085601f8301126101cf57600080fd5b8151818111156101e1576101e161012f565b604051601f8201601f19908116603f011681019083821181831017156102095761020961012f565b8160405282815288602084870101111561022257600080fd5b610233836020830160208801610145565b809650505050505061024760208401610175565b90509250929050565b60006020828403121561026257600080fd5b61026b82610175565b9392505050565b60008251610284818460208701610145565b919091019291505056fe00000000000000000000000000000000000000000000000000000000000000400000000000000000000000004f671f34d2d23fec3ee3087e3a0221f8d314d9df0000000000000000000000000000000000000000000000000000000000000104a97a8d160000000000000000000000004f671f34d2d23fec3ee3087e3a0221f8d314d9df000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000b7365637265742d736e6970000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002d73656372657431686e3834723975307533343233646d6a6a6739773065667877726168663776343439746b79790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
| ||
1 | 19,499,961 |
b34686d1a5cb518ac0fb0c9fac7700e43035466c08337778254ce67a6156858b
|
6542fa1ee29cceb07efe92fbbe3c02c02a4205facc1320038e60925a4725d32b
|
8ef829076a9d8e2194a2e675ea6d8f147c738a04
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
5e7a5c76f22199c25865ae97bfe506a31eeaae65
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,499,961 |
b34686d1a5cb518ac0fb0c9fac7700e43035466c08337778254ce67a6156858b
|
2b2e3117da33bc254f99aff243878c393913659e78fc8ebd5b6455d2d4ab4f62
|
82ccc769b300812f0e49be21b37d9a29e13b0b35
|
fcf68515aa6540dcd77f136dcb4f4ccd9967769a
|
f8a2cb4230760da358d81000f1eb3f15ef818119
|
630000335980600e6000396000f300755b7938945fd83eef3b338cb1648d6419c9be9625651bb2531459ca32a950c9aeecf3da49652d44284a2551a9c832534964a72229a310a54cc83a66be19bfeffbf373b9aed775dee79c733ff7733ff739ef1fd21d0e5af2e2c47100005e6b2bb3c300a0597fa234d128d6c3eecf965cd643d3c1cec99cb93c41f7242a2aaaa7de4df7770e7ed035c19c6a63be4efad44efe5a9ef1e4fbc8ccbf1bcce5b2da5fb98cfb13b5f7262a1d37080068af599b9938458ccc7edc25d0aac98f3639a497f36a07cef6b098d10665f2b1e4cf174ab3687df0fffc3cec7a74fef03dd2bd930f4d50f0f4d9ee8a3f15cff8f8e4919e9ca83367a904785af5df61ed206128ecda7bd10e2a169e9e3d131b582b00d1871bcacb3fc68be15e7f4e38eac07d66bc8ec07d2ce36810b770fed69039f1ae24e2f6e814ffbc0fab740a8ffdb6c52d2ad13c856a83be28eb5dc87bf579857aee16658eac919d452b4e8a288eac42fbf9e767b8aa186498d474420ca0b06bbf8c577639e467486a020edabd7737820339cfdef347204da47163ee907a7fdc8bf0eff3820b94a36f801881b6a14193af77438a6446523ddeb206e81b1a3fe5ebf732cfdcb95f9bc38b6a97a4984bd5983d8e4583913c7731c24f1093f3963b5c6bdaa8c1656c1f7cddae12b0620895ab9c2fb6bde7c015544b4033382268401554e42bee49bcb307391c3015e870c0991d46f9437fab0ad624fd0b49bb06dd6e1d33e1c8d247accff3ba218c93532db3889783207b6ad657d840f0bc07a6a0c144e7c35645b23790cd6594309fef78c8bbb8b5a5653712cd43740f69f7c3d47f5effb7b1e613e88304549d0a0bc1a2c4ae4a68db402a0b2970cad2c6799d42297487090fd16ede207fe086c932a15f1339c243340b79d5294a8de221b687882a2a68227fdb956a3c1129ce829e5b4d946744c0432c5e5d560751384d3a9fa2c22ee451fbc28781ecfd991df3fbd20ca4517a934fbdd0c78ebc78f5a5483aa02f5696598e65a7c1bf30e781fc4a8d5cf31c85cc071c1168828f22973630f4616a757b574c09b3245b9a6317320a251592ad66baa1f551d4015fae3d9b0c889fc4f8df192832dd1eb8607f14a0aca40865ab1911335d53709764fb9ad58a74f40fef897a5ef4a10a44583ef9e04dc7616179cced3e253b9c8d89923feee071c75ab96cbcc9a1d2a7d58fb904329f9efa72e3765555dced6d31d8f3d0921af2e3c05fafed78adeb32e3abaa7d9c63321f31c30d20f298d95ae64d010ede449391c0fa085964052b32ff6c1a6e9a285f601aeba6eddf3f0f1e709c974e907e2f3055dd8f8978c99909717a5a5efbca85772fcf6b3dc2a8f9f44ac9c5035127acff2290b5297fa7665c2f579a981e1ce1e9c6971ba648d79a8eb237dafe00685824d4715f7a3eb9c51adc468f0822758d59399659d5633a5f3791e42a1aa2e73cf2442e0d69a70ee9687f5705bfbc09f6b27eb18a057bac45a902ebed4c37de5a986ec8e11e9a1a9de327d214f41475440e78afde185bf1288f2c0a83a41e279a50934b1544caca2e881104b551727fbfbaf5876f4f0bb2b76e4bcef68f88ade7ae0d85e67dacb7d45e7c8e7548896e335fbab82f7a7782cf205f8e93cc89460fe257550f24557b29699a644537052d2f81f5c39d6f4727e5ece12a5382275c82a66d87c4ffc08d405f141f5850ea62a9df9fb6386792e59c125d99cbe99fd2766f38a9d0e69bad42bf3f57fbf63bdc41f9bd5e58e5565b28813900b8a8594da63214d71085df3e9ff32f82f43bdab2b73e08f661a661ff021743aa8c6f02734764025215515b0c1e2abeb45f3074c552173de19e30e8fa8913cf93be08f662d28a579f9363e4428a270e78c67950571ca98bde3c2f26bacca98430881d281b585c5a094fecefb1609cf14d4b22ce2cbb5b5bc3f72b3ac67bf3830e418775442fbd80b19703b8bbb75772d77a4bdbbeb43f83f87fbb4e4ef6c05738a552f7b7c17a9e59eeea2619151d58e3bd7f3316f0411774d29cca45cad8f43d33c436d15c91c3f0a53af11ed197c8abc9929e7ccbac4e66ae366d9d161bc45bba5086a63a23dacc92c1565d158228710e9ee816ead54d3237ca0af7e399be1e311fd2dd3194856f7b1e11f376b9e3f252c1a7969cb066f589ee00ce8ea24aeea0d73dca043ed2615835c473f4d5eff03f215c72aba796dcad42bd8b05bb678f73119f2ea0263f104177dfec391996f82853ab6ef9c8457fe70bf1410d0649f83f27ad0f361fd7fbcde367119f205282cb9a1a522569157593b96b2f4021dc4d51df424f0e7812124ee4059137243aaa83c868bc88eb2b8e6a4a9cbd95b96899e4d1bbe0d7e7d6e3dc417afc4b3c7907b3e61bf53b1d488abff91e8c5d75d796fd44479d7c013c108e954877f85d98a617e91fea9f7236a23cf726b54582e35ac7147785c1535b51e20f784237429d3081fa6eb2844fcd73fa5ae59086bfdcd92c656f0beee569370526103ac72f402fc03927e45f545fa22021a47f79fc7c9abcc9a3518e6bae51f50a42265609fd0e93f611df37e3a4771026fc4f7c4cea6f4fdb7fe59f404fda5e639ba1de0647573fadeb7145499f141663d9cd78d690d8638f21961cce9058cd7abb985a7cd7fa02ef5e531b4f23dfc8e7d8c0f3f98a66ce07b3faff54d88b9671f7f9615c3f80a3077a1ccf74e52f5a3f91513a92faeeb586c6db21a24d47aa4099ac5838c91733ea2fc54c6aa9e1eec3ac6843aa770e1c8f1c960f70f8e7c4255b918404ffe448b4f3f4494fa8d57195e2e7fcfbbd44f40bbbab1b244baa39b59e6029c4d8932a4824d9b5cf06d16b0da3db7245a6b9bc5172fa94aaa2d451f465a99fd501da915e7ec97f6a38faf5ccce16c461ec931fa5ee17404e53f43c1d97ae7326382e4eea86d88bab3f7db1f08405c26f366d5824f8827c9a9e59c164a2db27b4a72f5af55aec69f7abfc04fe9ca963ed6ea4bfd1f3caa41857d1e14d24727f2ea304e26c2a6b8bb5d23f685598a1f2395b6ec631356bbe13c5649c9c93b67454eeddd8e9f013a65f5327a0eab4b684599c85c486f2f86a8bb79c779dd2e0afbb09829ae3b75f3afbee5b6101cf7133d8404dc3238edf9ae1f69da24ee9c1b4abfd7d22ce2918d7fd36b810f8d8f19649e0db437e4c79dff0bde4206002b79ee40c52e3b2dcbdfa5330d58856ced3aed68f111b9e3170e8792448397862dfd8a5e2df41dd6332c4eb136f26c9ad2320fe388fa02e7f76138f40a4bb28687b2a44bfab5bcb6e40dd389b45de5f8578a9b6a483c7f1aff038ef6d3b6e8521e510065864681655a739e989ff2e08e0c19e89f8772896c856a1b60eaee9399eee219870832b232dea87bc95787a0e0973e8cbe70ea29f6e465b4d110c14bbcf9aaee429f7b1d952abc6dcf8fb593debd0e17d6e6e0bb7a1f930f38a031caebce71e71a2e79d40a02d9244cb61588627782037b8fb5cb9684744c5e4cac56c80d211eb1c9f5ca829161f43b38b383a8f91cdbcffd89252657e9c4c07d28fb42ad8a54b770d8f5fdccde32efd9e630473057126acfeb0acafdc4e085106210df7031c064ff8b4db6b6e9a4dc831b3a83e4c09dfafed2fcdcb1fe95270335c96b237f7067f58cd9c196c3fdf9bf2070e838eaa410d3d43023e1cb7732dfb7af0d7300966863cf42f85570c12cf70a4395c57cf075ab2ef97c6b3d8ad9121471424e0a021822c9fe2e797f6a7dbaaf3900e6408ce732b8b12100b5d53cfdeffdc5a7f9071cb21e0923aa5c425d11292c84139dfd58d1982bb48fbc409df440df1971702f83d9214577b2d3b0fa79f97d339b849b20bbcc3a4408a2ea5f420e534876a801347d395df7e75f739dfef268d60acf245a50fa1424e844103579693a6eca85313be478f6f4b2588f7a2a77680910f695e4b48096c45cb6152b7c87d22ac3b9a6c92ebc04534bb54d40c2d3756b6592afb3d42bbf3888d46ca53042cf637f3f2bcb8e3f5e220fe74c4bf6d1ec4801475cad51bd780855ecae28e818470f1b86eb7b2ee2ea33ee48721fecaf73ff6a65c89bca6ab6bf609e19027ab0cc9f2f209628738e20a4f637ee1f09f2e7e0208218ac3cf6cc0014c7049ac1beba31a06a68fac6fc9f8c5e2f8ba2224b04b7d668abbe55a812e3c9c8374f30b6bc7dd349e810ae969e582a342693b53ad5031bb5f5aad5f2a2c63f7c3701817310994f7ef5eb03a2a3ba2569c421231cb3be7d1b741afb9902c95da94abd0e79e80f58b183b7954946ae4813c1bfe7345d32282384b9fbfe429e6c071b14ec4b4c3abfe2c2278daebedcbbd8c6c746ea37685f13229a7f994ba6b36439e6dfcea36403669d7c67683eaa07ee7de50f8b8ed00a621e70ae962fdc2ae7d030ef37b4c2d9276e67b553f52c9f2e7f040b43c1067ccf084a6a6262ffda3a21a17847d2cf1e72885d8b7fbde23307df72994403b45df27de8939213e78215d5783837c1bbdc2516234b4798739c6e7d3a647d3cf9dfb96d1f58ed0afba430db22aba69c370c12b7f48c35b49fc3a77527ed57b5781554eb33592c864cafd775e3ac1054328b2ce21398e2d23c90e4765a8cfe0761554ad26c1422b87abee0cdf692bf208efd179d2eba8da670ef00bd6cd82a8255756b21c797160db0500971a756c93d8b7372ff00c59877afec0b6f3765effe277ab369a54def6eaf8ba13a1d33698f9089bf1958ce6278f2e7f4e4ba03da36cbd937cfa38eb6ba206f35453ad69ebfb84a356dca76574d07b43224fc6f8e6541e692dd0e77e0d772542dda945b181a4881c8bbe5bb4c18fe5723b721b462518c200a72c0c8644c906f244ef8e438b7f2e88e672d4ba4382b60634e9521a132dd007d5eb813129487c5ecdf129edb3f33e2b2c4b4e717239c53b90db2b630c0d2eb113df625ff0eb4ad45504053b50ba12fee6d21f337dd3103eca1b68e52b1611ee39baf2fbe6a93489528572ff8e5b0097d579c62ea7dec0a6a783f94d8ca97631f129d3d1ffa89f1014bcc0fcbd2e5b860a0a062d5af061f9aaf5e8d6b5189fbc03c9e9ca1f614df7fbaf758fb884ba951e964b6a1145e657b88efa09437fcfe760a781bb2422d16259686d92c567e015983c2c3bd8a6f892cf329cf4e5ebe428c7e147f5f3a568cabb8c036507d0ad964d6ff6eed8dc25652ecb5a328c141327267caab4c29450878992a71e34799abb2011b4643c7d9aab40bb9ba8e7774b049c00c5c7f7d6a382c201e3bb4b9b5f3b4d3b77f0ab693fd8f9b3ed95275360d79870f0726928b616fb4b654cf17d0456f458c5b9add7e55edf1187f8af3c1f34237052bf81895ac7df7ba2035598d9b506e2771edb9a45c515ba47cd876d831efe32ce408d79ae483bdef3db17689c1bb1b385551655943e5040e353d49e1a4fc5d6da6b37928d61ecc4acf1ab4741e1f26060ba5ed3c6d31c54eee2c07295594bb73fdf41fbbef3bf8249b5788a0f5843396105d7fe29d40d92ccf20a7c2ee0342c2f236fb2e77094016621d21e54f1d7556395197c822a7c8ac88697379e71bb2ba7114756be9d08b772f69ead64d2668d29c9cbdc70d78baf5a36eeea62b93d657b058f1b6cf55a646ab377da07f6c6dccc33a89fa8b273ec358ebfc178bd34207fac8736707cd0d3e8e94ebcb316c5bb4a000894c0d49dd5543e022771ffef2b91812a1d97376e7a7fca92f6d8f6d694c25723b6b28a5df57e341cb66f0ffded5946e95d9151f6da5e8fc52b644e184d35affb0d5fa9e5d7852807049d05a19e6ae257469ff6c7f904decfc51aa9a7af822b99b9e69b0cd737af1f2ea0c42d67abbf2f69d85161184a98f1ade2996ae65ff42e7aee1ffa89fbdd3ee6e779e998dbbc310f77d7b2256013cabcc1c96dfce20559297e6e72e831de20ab786f2ae5ee0c73325657314a151e7c882e78a5d52cbd4c9252388db9001ef211743de7e5d033195bd36ffe1e6ba0b9e24c969b65f65c1e2770876ed5cb38e0fb9eb292cc8c62e6317ffcd704b43e533161b7c0737a510aef033c77cecea00db3798262cd2490ae7ddd5abf89f57ddbfe590bdadf2e6794ee82f70151ceb2ba20e30ca1888e8d71041dafe10bfcfb26a54058b80782b57933defe6add5a103e37851c323ab80d9244aa5059af7fe4716b6cd15895caadf3dd6a755ced0339e347c6b78bdc6a843d52d843b593b4952e2966641f33d782c05986a28d9d5b92cadb1efaa61a9bf5ee5a0984088e17183ec350788e09e28587ef9cce3fedeae789fef8f7185bb4cc2d945f4f2851af07b30bc7ba3a5512f0d31b7e32567621c172657aeeb2147980db7a4e1d5b7b5d8e12c96edc7030afb32c0b11f48dd57cfec65e9d16627cb7fce480b53d54207cfb1a72db02c19db52dd09ca6ee4027397b94294a33f91d7ac45849f051769d5a238a2a9c7edcf6a653f0a72acd41c6eaaba1ace4600120ea2912ae2926ef15e2777aa2de67457013a0912fb326cc610812bbc76622a596df59f7daaf6f61e83963c56dfffe217395455c02b93bfc42f366bcd698e512599d6f0d7a44599b64a01cae903f285dd03f7decbe17a354c8077e976d9af51e05cfee36473cb0edc2e6223daf6a5af3e964cccb9977143eca07a8fd786a88faf7100d8d85a5a0337d3437eb829477f13c59979f4efdfe2a5ff64d13da7a68400212442cce11f3d33a98dba1ca8ccd920ff7206f5e56371fceb9af45de2a38f512955c6647b75d48d0800e4c96a971e52959bf4a5939cc2536d8aba0c26a7249c430b974f8314d5f7ddae8ebb22f3860204b19ec45fb59e195b04503c799277619bd632ab3b4413606719e2b22be37567fe7fd9efa33b497fad7d441979684ecee61c8f3e15feef4d13983329e2717abfe272483f052cb2f1a8f1e8d5725335fe982286dce07872fc9e029cf3023fcc413992b71ef99b996ac32ff04f47f279f3cbfd250faf0cf9efc5af1517dee8913e00e56b32c0872d2b6406af71b5f59651affa7e7b4a7abc1311d1736d297129c13f52fa45cc46cd999e96bec58968139caef70faf410667e96711df9df96cc73efa15fd1586d6b3b54f3319470dc97a39df42ddeaca1eb0965471f82e6d65f7cc543fb3ef19f99983f1f0b69eb7f65ff0c034683c8b799ebbd6923313085fe4d6c24890b5b36224f30d8be8723e616dbf025c07a9fed97fbc55f5de7cfb9a1a534d06f8ef23decbefa735ce3a5ae392c98766ea6f93273d289bdf06ef02cc352e1f6fe65d34b7f48cd341c843e59b56661f842ac24e7dc36a4ec19173f59dcf7222bb7ab507b1817f71e057ba795735dd08559dc23c2f6dcc595494d0ec985e4e0e16b36abcdec83e3142896f8c2a937fbe1583849af6c8991f8f90941a4c7718ff7cd823101eb86ad64e7cfcdf86006db603cc08e599e1fd346c63b52ce4dfe7972d36b8eacdb4cf3de351ca7c719f648ecbbf1c5cb8d841f5736f7ae8ff45a372a1488be92ee7b3d091fbca22167b06d248410f358a335af128bbd7e02ed70ae91e0fb5f70d06333abdcf575bef416f3d30e2b3aff4845e08ece9ac509a5fd2cbf9a1283863f66a630e6588dc26af9eaf5f18e589f3ffad203657383b778639a24dd632b939327767cd1b852a954f63b5bb35487a597210cfed59dcad0a28ab1a551e1ecc2ef0a79e22dfb0714b0b50aaf95545b5f45cb4c4bc812d4f624bed926bb49c22ccf50cdbef9cce150b74b9963bfe91f18d2a35201d4976d9a2ecb67b156fabd49ba72944325f7517d909fc1824ae8f8db34c34ab34a0ea590150beb1561282ec26cf4943c5e629bbc78293643d0f70cdb5c7990ee3539cb8fcfe61cab75a36d0f7c099c632edda2e9fd10da7aabf33a2872fe1c5ea6c5d6d50b60a637efb9121bb12e74efcd29da98bac98a3b168b34fc997c305a938c3ff610752e339555fb6910f33b67eebc6bd2811bad1b3f9995a6c82fa3da88851f9e1ccef0c0996be05126b2e2ea36c08ad3cebb97f6ead4f8f38d7496db2975d53048d70042cf4f37ee86ce05f4a03e0c335dcdd9f6d9f782c63d43c927a9dbbe19971899642c654c4cac47f615fd74618648453816a93bc490d061ac4c086af4a517d2c7356ccc1b5bf762f9973297ab9fd4a8b8cd8871b96af579cb28f26dba71df41137d2b9090f75568abf45327f4de81103e183d6e8595c842eb4fe1d3225d4bbf72e77c18f3d83c3dcb6e76a92a01c186b3530a63b66f54b979c7d4c73bb141233cf99377d1b4dc73f8cec9137ba04fac6cea840adf8eb4cc509b0c63aac5aecc7cde30b6409eb4ca323312d79c44ac2494374dc7e7f0e31ebaeed587b7bf3d31f7de621906339f32d5f81e7eaf042b6ff8fa9bd5db397de237171374044ffc95ecf4a75a7a176adb8f3f3f38ce0c80bf1532c30bde67d89a046bb2c42389583c46cfd67acd78c3c8fdf51fb2848860da53ec5d2fe678d180f62a0ea89b4aa46f8a315bf1e5f6294eadef5eb7bf6de3e26fc9417e786d6841da076c2cd709ead9a93b28acd380207beedca590e19991a57f5ff33b621377c678fbcf7db962c91812735dafd90f46dd271fb13c80defd759b48032fda244c29e995831fee808c70caab4362385b13613b19f66f8edec0bbafd36139fe9faedd2ab9e7b477393b7351a5f9c6970f6ee081e3a7596e147ec7bf75a3f1d34d5fc9b27623272edfc6d56fb83b23e83398d60774511502c022e1b8f2a2ab57243a9e78e0687b67c80beec32b1124af16010377e8e3ea317f7708a65201cd11184cfea2eec9613cf331f92e7e597f4f42a3071edfbe8f646b7f08e10650edc137342511a93849fae3b10dfbccb74ffbe997fdaf37e068260c083c58f0edea347ee99d0ea311e05ad91467b7da4db5749e33f71f86ebfe89cb8a8b1d204bc1d655677d18529dc27880a6d884879e9c69af0c99d07f36f7e4cdf1ac67679eb8d9507ef3d72f1aa58d5502080f9cef4f7f8cca0e3d1f1332d118ce9df5ec7cb9db0b0ed5d55c770e64ec2658c6b2423ede1ff5b9d2c5681f1a8c12d181a3db4b2db4338690069ef823c77d184ac754230ddd59f97f507675362676f5c46db77c5de7aba36981643e804c409b1c68ddcac272858f60b357f6fb93ab636d2e096d95bad7b930761218fb128e755dd65bbe2d94d0aa51c12f6f7e0606e96a5f23d15500da64f8967959a01994280860e2ef7791a455afeb636451b8cd82721484cb29b1497fb8941f37442c6550d5a7ab815fe2c57bf4b13809ba39178bc880c8afc7d7f2db7cbf7bb931cde590555cda6bd6140949c45824327555e835bdd1f47332e8e1c4338e20bdd2287b7d09140601d3ca52c322efb8ea862e380ed460b2a2616c8eeb2d601f6785c102885639ba20396eb9aeabe235f6633b341a8333631c066de9f439474ac05b028baa00e5f96f8b8e511970c1ab54b2946efea21641b0eef8211c3f80a92f45c67b8b6d9aada1bbf3f6ff8ed0b6433cdc5e13a4e15d0eac3cc6633b4b577d198e632f188ea43841a5c35e814e2065d904152b240971035aaf486d764d66a9326b0bcf6373ce14aaa9eb15772ea21324b43a56890c92364bd976861b47b81aa7fc8bec3ea081eee2a0dc668f2e9583f7a8b21f040d909021423d8c007ea07f98a2b32e2ce0791011032f16ad8b9a8566ff771cd830980190104107dd03e32b36a75700f7c10b660fb1f587285d3788247728ce1f83451251b49ff4c8f5950be81d178e5140cd6aaf11f73ca748d0c8dfaae33001cc1e842ec5317f44710813ae320b60539c157bd00d7af00cf9eeb3258d5064842def46ff07f07c053255ba4cd88d0031b3d3dbbbc752566d2176b41534ad119fff9674ef15789b4af88e276d56dc5009c432f62c13428dd18fe5880f617a06dfe678b5525937b9a23494c4bd135b7b0c754508595d6d3c66c55ec9df1a22e0517775914e99204b502d17c2015a2ec20753c982f2808f8ff26bdef879a331485381786e05e64828b00441b166578ca880a334308ed0d288ff566a522822c2599b7875cb91d008bec503626ed87a29546245f767ce7991b714bdc7309af2128ab066f8ef0829db0134b7c20f1428ed8fe8db1616ec8ff739d7b208feec005ed0cb1f40b645f11422bad899603739e29aabcd8163e915c2804364d4c81e6b2d94db17ccb6230439249d63b304ba3791699c39ac0369e7241d10a47c82adee41c101c69b2c35d943069616b1c0c0607d97ec69ffb34e50810612269f561f93c336898852783a9f07c92199135c3e9e5fd53e5af094c32edf98d7a4d65a9c2df7884a386b8439e23e0641ebdbcbce3763f65d90f63b0aee9db03b51c6c22b94fce3c7dccceb50dddd800ef7fde8d5e4dfd3b030e0085a2be0eb0777fb25d3c6e2629b5871c79cc1ad68622a29826fa0fdee474493476a7d5023a5a1329da33160b1ca9bb5d1ca631a9d6ecff82b4b9ae0b92e10be6541aabb3454244bfcd6e258e9b4cb1b1601b4104c717327f3b5313d9051a8a975edf5587f4525a06ddb4f9cb1d8ec1f495c9ae0474b05a4b8d02dc57078fe62030e0cef39fc5f9a4fe1e17350699308a11288fffe73b110e7472932fa8fa0a3d074f9fd0585df0c1b2d913efee75fa6554eb06688693c2c25ed4529afe6ebe0a330341910f351bc7671ef0181a0ffd48df872511c23dcb1aeb2cca390ed3ca70ebb46b457bbf87ffc9209ea606e81ba86e8733b10479cd5c67699f0fd9b004fe108ef57f36568fd745e479c62fe4b8ed8921cca23113c5b64f757b546242ce67d8b8c7f5f794aecda86724405f595e43c4b6017a10576e5f36aee655a76948633cc39dc614a1d0cf8d6ff6bca5e17f0a5269339ae1b345471d57b2c51dc6ac7812bf1a7b012cfae24b227c7c3fc3313e7d66e937b4a1f90555ec8c72b0912ce930a1f891453ecb70ba15bb3ff0310b8d44379764e2ced96db4d95a064f22b2fd603534d11a9875dda711e268dda299dad0ab6f24ae901de7152e275bc87cb56b74436c99e2abd0bdc05c9ef4da14bbaccde374dce2cb36c45817264de83ffd813f619432061622636a42aa7cb3ba43be96ad0aa56273d7d4fe3bb73f847476604a0383f169f2f21bd707e894adb53f02d8d89b9d1738ccea718c217d60a3307debe641569d1198430ee70b977920db8cfb810e03ddc9ba9db3b227b713e13e71901fa4c1fcc4eef463cdb85fbdc20b3769c6b20fce5ddc83b7205322fd5e71c954596768360621098eea95a3562bab693be9f11e3c6f9f58cc918442c0cb349e0e0a4866126e80b52fcf2cc176f2c30058df8ed57dfb3ebdae702b5af7e36098a6674e3147f6c696a9ed17365594a098ee82a85791bbbfa5c05ffc80ed94cd60b4365ec13f35b307e08bc3ea34742acfe0fa821cff95811509b009acd2eb14636448858fcc88286127ee5a77c9ff3c0e736ae4de483cdb0bb10a4aa4c49953c50868236adeb0aaeec10c188fbcc56821b74731fa9136c76fd3e65a2a732a8c611dda07e7ee21dc2a45bd626027b8cdd8608ff35347850edc6965d5911ccba89340b070c0563e8b2f802258753ff9d8dbe2a88da6abe08d84fb0f9b7aa4fc84c61238815f6af49faa0f151092f14a4e4a5c3d1f2fedf85ffcaa880219a436ae85a6708bbeb24fcb392f0671ff766734ddf4666d260d74ad06a47498e4773ba5852feb96cbe59b9822356c3015c564143f74739f71136bbe0d8b3f8a7b8fa074d42f4dfd3f777528db8553253569f1fca07629288a348502ec91e03fe4a43e961753c795c5651da762ca83c04f293320b4cad39e406178e5da34bd213909bff95cc09836ee4ecca4c1d52d5656106cf1381fc6676958ae0298ef8044656e549cfea121cb62bb2ae3be1377fdde8fb7976dcdf91e0b9aa726cbbc9a6ff2f3a11fc1dc167614a2ffd1836688fc826bd1f8509b4d927f87d255548b171b78bf1bb31b579851c295e2196efdf031676026f7b1212bac995b01fb9e5945857581572fae4a692ebad8d0f928d7e22f01f8e97771dc13191203962214908da1482f4afe57fd1f9834cc5e2e0ad61dde479d5b47561aafb76a847787353751cd5658d530489c5518d3005a4babda4d44d4953c70442e7534534bd84f967f162939254290cad169ed6c16d05ac8396e1fbee5e6935d0e7f496d9f8728e785a70e29988e62f9644797829eba57eb9c60f11fead1a2299eddff8826a606ced412820768bde5a702d10db06165e33b53149eb9ff1d315c828565702fbf9fadb16d6c167c141bcee7d70dd09d3973a799566c0f9f316b8152038e18c93f5e21202df61ea465ea89117a4896b3f40d5850cee00d6d446f3e0f7f919a24016453c1f27298c5c33c473491d46e4cace6d69d79e283f0e134f02bbb55861fe57bb99fff6f24b7225dcf6a0cee5c0d8c7e78567ed92ffb2d965cd6d6bf922cc3ff430a94609c90fa7e9e9e51f22a8410b7e99a9dc48365410f2f8860841fae712b21ac8a7427dfc00fe799d70e9dfee6098e80eba462b9fc3fc0be1b5c6f24c187a3b4228bbc5eb7e03e6fdeb57c0ce35509cccc01122b71488667a71337722d5e54479e314d6b1dc0e0a1a7a9f0813e753bbc7d473bc54eb5428827df711cd84cd772b06cb918fe187e861f9a05c00769a483981e1bbc8eabf31234f70899bf296e9fbce985efa00f9a48c68e286bdc1e820c775e5dff00d25d50552f5a14d96b596239fc1407aa884ab212e868284ae5bbc6c40aed157a7bc5c20362bb3a33f5671c4b42389c4462cf2270d067dfcb495ecdab07c66555d3c3be0dd1ea33515fcda702d679dd6cd29dd3edd045e1c4d055710d7c282580f56ee3f0a246128960b71d91f56f59f7b414bb1b20ef244cf0e662aebe3e3122fe5c716666019f266ddcc400cfda377f2c637018c2b5cffe0aa529fad242737120cd1e2de9d180bbc89280965151102a648176e577940d7e23fd06b489e07e33d7d85555992a0faccae1b0af37bbf4e1cafe82065c20fd0aeff70021de42b9b3ca96e270796015561c27216b04cd84b92720155f226334758f6c15293fdda860885bf5baad60a58bde249dc2e42e4529c2aad241833594abdc4431897fbca2887030293e62da098ba2d4d71e84f7790adb0c48a0e666d15b7d2f9b541ac81f735c149ad1ef3ac56cd9ffb4cbc5a05a68eb2f5bde9512bee3f72d9629730c7f24ef6a79f126a75cf69a0fb3c0e9c07d3a17c84466016dbb72e2deaf588f39b2e245f75f1d8abb4986701dcbea2c6c7203e422768bdcb5c652e98761f188fda93d6410e334cbbcee016ee13e572e072ffaea04281fcb62117d70d595f3b9f51f7e1778205077f8ba541991ae94a8642677ed17141e02847d9b72b99cc7bc0bad3109f06434e469ebb393c77f529e21f54c71bcfe804b3b7797f9b292d02dcfe40d96eae078dd1e5e9fb30d8b6e265f61a5df98992c879284dc37d9d118dd1bc13b265c50ae14b5b20abbc5722de00e7ff0e0a53411d0fe517279954c34231229599899eeea55ab41fc268aa10291e8cba9a94f58a5d7d6ca82b293d35ce90e22262e2d26c8ba6686a962863da915bf044eee622085fdc9c8ad428ea76b29466d7d6e60c1cd8b5ae73d306da810a76795ef4d2e8144f1818c11034565b1a821e70da25379ab49b7365f519d1daac6ec3df3493ded0fbdfd83b20a8bedde03b757969b6d2bb5bca2a9aa05690649b88cf436c3061281ee83c77d89f63af24906b505ae01cfd8c88e631f4eb93e9dfd4ad8c03d75ac531789b540cac177616dd2aa4b849eff296b87f3824563dcc390af78bca69fe5e895a8280eb6a7d4ad25b2eb0e8a5facf483b8253e690a220ff5402f1293c308ce1ab136c3f56b670259e5de2e293730b380cfeaa08c851140cda837656c65f418b61a6b74e5faa2272969d02de0627965245f849f4b5fdc8303d34fbba4536107cc91fe40e5d68c47f81ab87f8307a808f72d63e2aba47e308921745e0085abdc82f2ac7a6cf8ab3c02828add28995b51ec87ffec35dd56994ff5905183e6bd4197849dead1a140af3eb8b615ad54b827962a2bbf828c7a0b4b1dba003d7473f27906ce42054ca9df00f37edd35886dcd4bf0d4b206dd08a3a46d58be7e30b25240568ad142a98953821ddc60713cb76237f8a599a12e7a4360a6745534c19c5be817244299e52a56ff5701ef081b5990b5f04a780361fe582122147121ee2341183035a15250dee83895d9a4c5cacfc62c5ffad10a4b6844c195fe0df22d8d7f55bbf5c59a42f3c4ac9b5e73ee02c0b062d3690ea22725497648bc8986ebbeb48b1a2f03f7b4658aab28cde4205fe122e848687ded1946fbb238265fcb9da4558859cee26fa1ed9e4c1d799b0ef2b6aeb703fbd138d60b545d3331f2404e2a669cb3eb54fd845f90e6272e167518403059acab5684521275859b82c91cadf5bf5dfded690d5ed46933a3be70c7456c1e0c2b28423419e2a8ef778ae421a43e981af282745f03cffb5661e171507bd4b9b2a7d1a3cfd977596e21b85d83d2981681c0672855241d14227b9148da55f253e4f9ac4a57918546fd29b66fcb564a14a183cc1aa0bd72b438d5b067aaf4d51e24ca0a1688cd5700d225dc4624802392f8cec372c9bf2fa038b6ec32ea02ede366d7186f82896b066586266fc05f368fd611fd17a1b70594cac9e872285696dc6892d644e4b004ee2fae206edfe8b26c31fdeb74f18e2878489035ebfd1bf432b5cd79e7fef14c127c4bd0d064739c146e7cfb3c2413a864435686497e91d782d39aa8b6c0a19375a438d57507d06a06fb03c358e7be3afe3bfa562af72d07a328ae21d3f6a4ea8ef87053ef5903d21414c180b6933a8877de4ee701a54809321b3fd63ffeae06f8f76f1f321a85a14b21bbaac5c162177979e347de2a51f45ea5ba932e12d45459205531a44b943278e470b3c38e28c08d676812565029f12d537cf1a62cda5ed04d32a7a940b8ac894c8a3220f22830aa35ee57088d51e83be8c77be74d9c7ea8938a0bd31251274b5085e0a8bb73f8be0ebad9125e4ad70d65b0227051ade824c65b6bd25b88732762b0111f4ce4b9541551114f2116456023503f4c043a45126880c5b3d54c643fc48999bd4899d70a5234b42fb58f6ac63c8f14e8d34fb0be616a61bee3e9495b6dad14c357624d05922a140b423b45c1c7217cef1e41dc1133d503381331dc6def2d430b6ba39ca86a46a7f1fa135714ad87ffd2ef10bbe97ae30fd3c870bdf7100e35e2542656dddab44e05a31c21097afe2d3e7cd182f86dc3e717069c6ee7cb76818661db39bd5f1bca83e5494b8342a7be79b7b03ed9449c1571fe7a847e5a616bbf105cba6d36baca5cc178c836c5dedd9a9722282b4e62aa2e66c5567d86106359967bba00394c75db694e0707c82391a5d6cc63a507eb10aa5cdfc3c2ee70e2796a8618212e3d1c41286eb9773f4a9d8493a4b0bb75154308b21e83834e05a9a0c67ce602e5d7d22dd19f334f5e9aeacd66758ac95f8e09038b2c0764611e4eb5b82dae8ef382b79cf8f72b50a2484a7c22710ebdacbbc0bc75dda54b024508436f664c6c7040814b71ffbe97e8430dc53da455ac347766a2b948de1cbaa0e21ac0d0d56dd09df9f27c9f567bcccc9d9a1c935fed88672b41b23bbfb4ee0fdb9f8db74b77244b11c8e62d7db08b3a2e21d629db78b6907baf8fc9281ea6c7c50a9515b2606e6c861dd8bf94b9d11fa11f6a2b300ff63ae268dabd58069c661b897492b864d3567324514ad1fc06df68260f5c52ecd50d54d113d7479f3ca4b44ff6ada79642fe93a6f9f8f2876fd48c5691b268b1cf2a552a7f4f7ac2b17605bb02e70643c44e87669a3f34312af97fe95bd1a7e9e4576c35eb8152b4fab3d60ba2186652fd8b24bd3e55766ea0f5fd31086d5cecac0038ce4113baf855ebb531c493c515991552e48ec816236c82689d99a8b1b5fbe6e2ba8e4dd6fa2a7529be0522f1280a9a68abc4870eec33dc8127961eadc8ed37e4c3fb3cdd6aa9d7069e38fd175bd648dea3966bdeff14bf66fde04f2707e093ab39277f8382eaf3a8601fae4de58ba20cf6fc265e03d2893de26ab55f6008a84a964fac6278bb7a68c9dface1373c40e1ec8338db791a1e900398077c02a6acb7de47289e8cffb3502e75eaf9b0ae028cc09a707c84f7abcba1a87a19f92ab328115b878e2bb854b17f2ec8229c1ca7882e98b46ce2e5cd83a1be21d829b2d522118ef718056ae6e2356c9517ffa52fa8fff1adceb30e01bcdb831e1650ba4826d0a58989aeae1b8ba0efaebc1fab447a7c8e51748b2f09dde2b4de1e68a82a61632a40c538664e2d7680e07f0750b587080474f17e596e58e72cd99f8f8fcbac66a9c90a89d5dbcbe3aad676f708f5de5723d06851cbc8b110118aa8e08f155b5499ef19ca0a8e7f4d920d5d0c11fe60c19ad8357a141620799d376951b3aab4259721129038aa0f72110622cee0becd734b765e44af6efb2795bf6723173d9e066e3bd5f8579dd22b44fb6183635661a7b7946fdd67cf8033efb2ce487f11ced3a2ed07e4b99244350a6e83821973769f9a9021a4f11f97125f6483abdbf98a470967004fde021e818bb7edffa28a4b70f68662e96a91d482c77787c40126e9b09ea36c1bf78acb7f73ec2e817a1a8a8004b4e0ab5df68bd68ef5030cddd997acee106d9756b7c73bbcc8d25facb87a6973c1e22218c3f19fcbbce6960a8d38062f029582a78b74615c88b3d7f7ec9b4f6f2fc1eb101b7ab2459a847d789a081c6dfd06b1cc651c621cd88c2666ae0fcfbd9052ea5e6335cf5eed05f8cf7f442e2cc8b3bdbb24e3066afab50d49429ce5381b198dacec81c38280c10e37a3dadf6954e2488d6bcffe8a12332200a4fad9637464b5a1dee1505bf5428ce2ec80d174289018600a52913cb4bb4cbe5de5b2d0a7518fc2d88d258c8e7ea4bc221f7688ab784640a61aedaa6ad79f7919616d8bd92c5fbe78748ca7545ff8ea5fbf46a5554a63dfd88068750c6eabbdc2cc1269b416293e0c92a154adb6689e6dc218dc75d084990339e108e09caf6f661c84214c4a5b057fb08a518e15b5a42d7576e23407e8098aa45b19d5dc87f9e486a5b757101fabf2412d48ab90bd5450638297ab1f21701e2846812ad3bd6c8c66f367c8d9b05177d8db5109876124c55268d0f3d59e15d569727cc2bd8856308254b9cb6250df4e65d5f4b4d096b6b837a450bad04cbf5bf91e6c88dd1686ea84709e01067c227d1e5df6bd4da31fce9ebf760d712a83367b5d7d6cafabad85c646c94e4b61f9256561381e12c198f7c84f85c51f98e7dcf25d5abbfa9ba6333ea2be1330b3fc2e7b3a7567d3d85f4a36da772e8032527596cdebd076ab2f4f9ae353fd7bf1c222d7d9cdccd079fea4e99a44f8655155b7518dc8b8484c74e693d249af3c4b80b01f68c2a64bffc5cecb8d23be667d2b605e3f0a47465701b47fc7971e0c8c5d0ccc7bd15a5ea98d06ba30a7cc5556b3770947e8850b1ff51d04dfd8da1e5cc57170ccc1512a13b0e9049bfbfcb123e4d34bae96f7538ff678ded58c235ad47f9ac76258495eda5c17b92e7e4b6e7f417183f160148c7683ad5f59f6f8bd919927ef14b5155cd3b25cd39d758b11120043d1bb94fa2d2787963635cc470e309770efdd15d80ef3118d0411106c39f7957937758ec64e1b64205d509d6f7f5afce92396f30f24df294d2ad8febdf58abbe3dba55e3430ea31561ad97076932b69edaf2e9eba4ca7ed15246a6fd0ebe96bf8782cc6f97ae7df670368a144860f57dd96398cf1133b163f9d76286b2474c5cf310ee250e81fb38288bc35f9a1decf80a17dee6c4ccde5758139dcdd63165d3ec0713eac86e59cb4d0e2a16eaffaa0f210d109b4a98aaf704dffe733540289aa2628979d7a2a40c70040fccec745d30edd99eac481da153a266ecc8bcc2a65f83edcb4ba4174aa6909e016835e491a0fa671b36282a83c6f3bc809012ff5a12ffa79b7fd79af2373f0c91fc108ddfaab3be519fa59c28827c7901211cdbc0f00cf4fe04cfea8b1b339987308a209513717962d278bee59a37d1598207356cb1e659fc0048480253d5d51a5962bee3b7c77f76702da47b9be5c8e46a96941ae43a832b7c9418fd371429e7f4bebaccefc2b272f35e7ed666761dbb9f8ebd2b6557db75a2540995f03b3cabf406adabeb4db79dee7d86f63adafe6e4d4ae49789d0b761c75cd9f6447df5f77b82d461fe3b318f0ba74fdb514d3e15bd0dce5e8be50e98dbf8ede829c73628c4759fda43aba8ec50dd5f2b3f0a9bf34ae76bd708f6749b425ffe361b76007e172a247bef5fe1c29d72dc93436e82da572b154fae7c4abf75afa68d8d053f65e13d92f17c52ca3ec72d762ee542e31f85588dafa7d87eb6d39720bf458effdc6f4260febe0cd2ebf56ad09459820287c212d05602b3c9297bf8656c44766f670d5f2e4183889a50a6badcf8e9d39cd1bb9a3f0460884551db00137cce7ef9d1faf0c00cfb3f99accd0f9a3d342526fc0f
|
00755b7938945fd83eef3b338cb1648d6419c9be9625651bb2531459ca32a950c9aeecf3da49652d44284a2551a9c832534964a72229a310a54cc83a66be19bfeffbf373b9aed775dee79c733ff7733ff739ef1fd21d0e5af2e2c47100005e6b2bb3c300a0597fa234d128d6c3eecf965cd643d3c1cec99cb93c41f7242a2aaaa7de4df7770e7ed035c19c6a63be4efad44efe5a9ef1e4fbc8ccbf1bcce5b2da5fb98cfb13b5f7262a1d37080068af599b9938458ccc7edc25d0aac98f3639a497f36a07cef6b098d10665f2b1e4cf174ab3687df0fffc3cec7a74fef03dd2bd930f4d50f0f4d9ee8a3f15cff8f8e4919e9ca83367a904785af5df61ed206128ecda7bd10e2a169e9e3d131b582b00d1871bcacb3fc68be15e7f4e38eac07d66bc8ec07d2ce36810b770fed69039f1ae24e2f6e814ffbc0fab740a8ffdb6c52d2ad13c856a83be28eb5dc87bf579857aee16658eac919d452b4e8a288eac42fbf9e767b8aa186498d474420ca0b06bbf8c577639e467486a020edabd7737820339cfdef347204da47163ee907a7fdc8bf0eff3820b94a36f801881b6a14193af77438a6446523ddeb206e81b1a3fe5ebf732cfdcb95f9bc38b6a97a4984bd5983d8e4583913c7731c24f1093f3963b5c6bdaa8c1656c1f7cddae12b0620895ab9c2fb6bde7c015544b4033382268401554e42bee49bcb307391c3015e870c0991d46f9437fab0ad624fd0b49bb06dd6e1d33e1c8d247accff3ba218c93532db3889783207b6ad657d840f0bc07a6a0c144e7c35645b23790cd6594309fef78c8bbb8b5a5653712cd43740f69f7c3d47f5effb7b1e613e88304549d0a0bc1a2c4ae4a68db402a0b2970cad2c6799d42297487090fd16ede207fe086c932a15f1339c243340b79d5294a8de221b687882a2a68227fdb956a3c1129ce829e5b4d946744c0432c5e5d560751384d3a9fa2c22ee451fbc28781ecfd991df3fbd20ca4517a934fbdd0c78ebc78f5a5483aa02f5696598e65a7c1bf30e781fc4a8d5cf31c85cc071c1168828f22973630f4616a757b574c09b3245b9a6317320a251592ad66baa1f551d4015fae3d9b0c889fc4f8df192832dd1eb8607f14a0aca40865ab1911335d53709764fb9ad58a74f40fef897a5ef4a10a44583ef9e04dc7616179cced3e253b9c8d89923feee071c75ab96cbcc9a1d2a7d58fb904329f9efa72e3765555dced6d31d8f3d0921af2e3c05fafed78adeb32e3abaa7d9c63321f31c30d20f298d95ae64d010ede449391c0fa085964052b32ff6c1a6e9a285f601aeba6eddf3f0f1e709c974e907e2f3055dd8f8978c99909717a5a5efbca85772fcf6b3dc2a8f9f44ac9c5035127acff2290b5297fa7665c2f579a981e1ce1e9c6971ba648d79a8eb237dafe00685824d4715f7a3eb9c51adc468f0822758d59399659d5633a5f3791e42a1aa2e73cf2442e0d69a70ee9687f5705bfbc09f6b27eb18a057bac45a902ebed4c37de5a986ec8e11e9a1a9de327d214f41475440e78afde185bf1288f2c0a83a41e279a50934b1544caca2e881104b551727fbfbaf5876f4f0bb2b76e4bcef68f88ade7ae0d85e67dacb7d45e7c8e7548896e335fbab82f7a7782cf205f8e93cc89460fe257550f24557b29699a644537052d2f81f5c39d6f4727e5ece12a5382275c82a66d87c4ffc08d405f141f5850ea62a9df9fb6386792e59c125d99cbe99fd2766f38a9d0e69bad42bf3f57fbf63bdc41f9bd5e58e5565b28813900b8a8594da63214d71085df3e9ff32f82f43bdab2b73e08f661a661ff021743aa8c6f02734764025215515b0c1e2abeb45f3074c552173de19e30e8fa8913cf93be08f662d28a579f9363e4428a270e78c67950571ca98bde3c2f26bacca98430881d281b585c5a094fecefb1609cf14d4b22ce2cbb5b5bc3f72b3ac67bf3830e418775442fbd80b19703b8bbb75772d77a4bdbbeb43f83f87fbb4e4ef6c05738a552f7b7c17a9e59eeea2619151d58e3bd7f3316f0411774d29cca45cad8f43d33c436d15c91c3f0a53af11ed197c8abc9929e7ccbac4e66ae366d9d161bc45bba5086a63a23dacc92c1565d158228710e9ee816ead54d3237ca0af7e399be1e311fd2dd3194856f7b1e11f376b9e3f252c1a7969cb066f589ee00ce8ea24aeea0d73dca043ed2615835c473f4d5eff03f215c72aba796dcad42bd8b05bb678f73119f2ea0263f104177dfec391996f82853ab6ef9c8457fe70bf1410d0649f83f27ad0f361fd7fbcde367119f205282cb9a1a522569157593b96b2f4021dc4d51df424f0e7812124ee4059137243aaa83c868bc88eb2b8e6a4a9cbd95b96899e4d1bbe0d7e7d6e3dc417afc4b3c7907b3e61bf53b1d488abff91e8c5d75d796fd44479d7c013c108e954877f85d98a617e91fea9f7236a23cf726b54582e35ac7147785c1535b51e20f784237429d3081fa6eb2844fcd73fa5ae59086bfdcd92c656f0beee569370526103ac72f402fc03927e45f545fa22021a47f79fc7c9abcc9a3518e6bae51f50a42265609fd0e93f611df37e3a4771026fc4f7c4cea6f4fdb7fe59f404fda5e639ba1de0647573fadeb7145499f141663d9cd78d690d8638f21961cce9058cd7abb985a7cd7fa02ef5e531b4f23dfc8e7d8c0f3f98a66ce07b3faff54d88b9671f7f9615c3f80a3077a1ccf74e52f5a3f91513a92faeeb586c6db21a24d47aa4099ac5838c91733ea2fc54c6aa9e1eec3ac6843aa770e1c8f1c960f70f8e7c4255b918404ffe448b4f3f4494fa8d57195e2e7fcfbbd44f40bbbab1b244baa39b59e6029c4d8932a4824d9b5cf06d16b0da3db7245a6b9bc5172fa94aaa2d451f465a99fd501da915e7ec97f6a38faf5ccce16c461ec931fa5ee17404e53f43c1d97ae7326382e4eea86d88bab3f7db1f08405c26f366d5824f8827c9a9e59c164a2db27b4a72f5af55aec69f7abfc04fe9ca963ed6ea4bfd1f3caa41857d1e14d24727f2ea304e26c2a6b8bb5d23f685598a1f2395b6ec631356bbe13c5649c9c93b67454eeddd8e9f013a65f5327a0eab4b684599c85c486f2f86a8bb79c779dd2e0afbb09829ae3b75f3afbee5b6101cf7133d8404dc3238edf9ae1f69da24ee9c1b4abfd7d22ce2918d7fd36b810f8d8f19649e0db437e4c79dff0bde4206002b79ee40c52e3b2dcbdfa5330d58856ced3aed68f111b9e3170e8792448397862dfd8a5e2df41dd6332c4eb136f26c9ad2320fe388fa02e7f76138f40a4bb28687b2a44bfab5bcb6e40dd389b45de5f8578a9b6a483c7f1aff038ef6d3b6e8521e510065864681655a739e989ff2e08e0c19e89f8772896c856a1b60eaee9399eee219870832b232dea87bc95787a0e0973e8cbe70ea29f6e465b4d110c14bbcf9aaee429f7b1d952abc6dcf8fb593debd0e17d6e6e0bb7a1f930f38a031caebce71e71a2e79d40a02d9244cb61588627782037b8fb5cb9684744c5e4cac56c80d211eb1c9f5ca829161f43b38b383a8f91cdbcffd89252657e9c4c07d28fb42ad8a54b770d8f5fdccde32efd9e630473057126acfeb0acafdc4e085106210df7031c064ff8b4db6b6e9a4dc831b3a83e4c09dfafed2fcdcb1fe95270335c96b237f7067f58cd9c196c3fdf9bf2070e838eaa410d3d43023e1cb7732dfb7af0d7300966863cf42f85570c12cf70a4395c57cf075ab2ef97c6b3d8ad9121471424e0a021822c9fe2e797f6a7dbaaf3900e6408ce732b8b12100b5d53cfdeffdc5a7f9071cb21e0923aa5c425d11292c84139dfd58d1982bb48fbc409df440df1971702f83d9214577b2d3b0fa79f97d339b849b20bbcc3a4408a2ea5f420e534876a801347d395df7e75f739dfef268d60acf245a50fa1424e844103579693a6eca85313be478f6f4b2588f7a2a77680910f695e4b48096c45cb6152b7c87d22ac3b9a6c92ebc04534bb54d40c2d3756b6592afb3d42bbf3888d46ca53042cf637f3f2bcb8e3f5e220fe74c4bf6d1ec4801475cad51bd780855ecae28e818470f1b86eb7b2ee2ea33ee48721fecaf73ff6a65c89bca6ab6bf609e19027ab0cc9f2f209628738e20a4f637ee1f09f2e7e0208218ac3cf6cc0014c7049ac1beba31a06a68fac6fc9f8c5e2f8ba2224b04b7d668abbe55a812e3c9c8374f30b6bc7dd349e810ae969e582a342693b53ad5031bb5f5aad5f2a2c63f7c3701817310994f7ef5eb03a2a3ba2569c421231cb3be7d1b741afb9902c95da94abd0e79e80f58b183b7954946ae4813c1bfe7345d32282384b9fbfe429e6c071b14ec4b4c3abfe2c2278daebedcbbd8c6c746ea37685f13229a7f994ba6b36439e6dfcea36403669d7c67683eaa07ee7de50f8b8ed00a621e70ae962fdc2ae7d030ef37b4c2d9276e67b553f52c9f2e7f040b43c1067ccf084a6a6262ffda3a21a17847d2cf1e72885d8b7fbde23307df72994403b45df27de8939213e78215d5783837c1bbdc2516234b4798739c6e7d3a647d3cf9dfb96d1f58ed0afba430db22aba69c370c12b7f48c35b49fc3a77527ed57b5781554eb33592c864cafd775e3ac1054328b2ce21398e2d23c90e4765a8cfe0761554ad26c1422b87abee0cdf692bf208efd179d2eba8da670ef00bd6cd82a8255756b21c797160db0500971a756c93d8b7372ff00c59877afec0b6f3765effe277ab369a54def6eaf8ba13a1d33698f9089bf1958ce6278f2e7f4e4ba03da36cbd937cfa38eb6ba206f35453ad69ebfb84a356dca76574d07b43224fc6f8e6541e692dd0e77e0d772542dda945b181a4881c8bbe5bb4c18fe5723b721b462518c200a72c0c8644c906f244ef8e438b7f2e88e672d4ba4382b60634e9521a132dd007d5eb813129487c5ecdf129edb3f33e2b2c4b4e717239c53b90db2b630c0d2eb113df625ff0eb4ad45504053b50ba12fee6d21f337dd3103eca1b68e52b1611ee39baf2fbe6a93489528572ff8e5b0097d579c62ea7dec0a6a783f94d8ca97631f129d3d1ffa89f1014bcc0fcbd2e5b860a0a062d5af061f9aaf5e8d6b5189fbc03c9e9ca1f614df7fbaf758fb884ba951e964b6a1145e657b88efa09437fcfe760a781bb2422d16259686d92c567e015983c2c3bd8a6f892cf329cf4e5ebe428c7e147f5f3a568cabb8c036507d0ad964d6ff6eed8dc25652ecb5a328c141327267caab4c29450878992a71e34799abb2011b4643c7d9aab40bb9ba8e7774b049c00c5c7f7d6a382c201e3bb4b9b5f3b4d3b77f0ab693fd8f9b3ed95275360d79870f0726928b616fb4b654cf17d0456f458c5b9add7e55edf1187f8af3c1f34237052bf81895ac7df7ba2035598d9b506e2771edb9a45c515ba47cd876d831efe32ce408d79ae483bdef3db17689c1bb1b385551655943e5040e353d49e1a4fc5d6da6b37928d61ecc4acf1ab4741e1f26060ba5ed3c6d31c54eee2c07295594bb73fdf41fbbef3bf8249b5788a0f5843396105d7fe29d40d92ccf20a7c2ee0342c2f236fb2e77094016621d21e54f1d7556395197c822a7c8ac88697379e71bb2ba7114756be9d08b772f69ead64d2668d29c9cbdc70d78baf5a36eeea62b93d657b058f1b6cf55a646ab377da07f6c6dccc33a89fa8b273ec358ebfc178bd34207fac8736707cd0d3e8e94ebcb316c5bb4a000894c0d49dd5543e022771ffef2b91812a1d97376e7a7fca92f6d8f6d694c25723b6b28a5df57e341cb66f0ffded5946e95d9151f6da5e8fc52b644e184d35affb0d5fa9e5d7852807049d05a19e6ae257469ff6c7f904decfc51aa9a7af822b99b9e69b0cd737af1f2ea0c42d67abbf2f69d85161184a98f1ade2996ae65ff42e7aee1ffa89fbdd3ee6e779e998dbbc310f77d7b2256013cabcc1c96dfce20559297e6e72e831de20ab786f2ae5ee0c73325657314a151e7c882e78a5d52cbd4c9252388db9001ef211743de7e5d033195bd36ffe1e6ba0b9e24c969b65f65c1e2770876ed5cb38e0fb9eb292cc8c62e6317ffcd704b43e533161b7c0737a510aef033c77cecea00db3798262cd2490ae7ddd5abf89f57ddbfe590bdadf2e6794ee82f70151ceb2ba20e30ca1888e8d71041dafe10bfcfb26a54058b80782b57933defe6add5a103e37851c323ab80d9244aa5059af7fe4716b6cd15895caadf3dd6a755ced0339e347c6b78bdc6a843d52d843b593b4952e2966641f33d782c05986a28d9d5b92cadb1efaa61a9bf5ee5a0984088e17183ec350788e09e28587ef9cce3fedeae789fef8f7185bb4cc2d945f4f2851af07b30bc7ba3a5512f0d31b7e32567621c172657aeeb2147980db7a4e1d5b7b5d8e12c96edc7030afb32c0b11f48dd57cfec65e9d16627cb7fce480b53d54207cfb1a72db02c19db52dd09ca6ee4027397b94294a33f91d7ac45849f051769d5a238a2a9c7edcf6a653f0a72acd41c6eaaba1ace4600120ea2912ae2926ef15e2777aa2de67457013a0912fb326cc610812bbc76622a596df59f7daaf6f61e83963c56dfffe217395455c02b93bfc42f366bcd698e512599d6f0d7a44599b64a01cae903f285dd03f7decbe17a354c8077e976d9af51e05cfee36473cb0edc2e6223daf6a5af3e964cccb9977143eca07a8fd786a88faf7100d8d85a5a0337d3437eb829477f13c59979f4efdfe2a5ff64d13da7a68400212442cce11f3d33a98dba1ca8ccd920ff7206f5e56371fceb9af45de2a38f512955c6647b75d48d0800e4c96a971e52959bf4a5939cc2536d8aba0c26a7249c430b974f8314d5f7ddae8ebb22f3860204b19ec45fb59e195b04503c799277619bd632ab3b4413606719e2b22be37567fe7fd9efa33b497fad7d441979684ecee61c8f3e15feef4d13983329e2717abfe272483f052cb2f1a8f1e8d5725335fe982286dce07872fc9e029cf3023fcc413992b71ef99b996ac32ff04f47f279f3cbfd250faf0cf9efc5af1517dee8913e00e56b32c0872d2b6406af71b5f59651affa7e7b4a7abc1311d1736d297129c13f52fa45cc46cd999e96bec58968139caef70faf410667e96711df9df96cc73efa15fd1586d6b3b54f3319470dc97a39df42ddeaca1eb0965471f82e6d65f7cc543fb3ef19f99983f1f0b69eb7f65ff0c034683c8b799ebbd6923313085fe4d6c24890b5b36224f30d8be8723e616dbf025c07a9fed97fbc55f5de7cfb9a1a534d06f8ef23decbefa735ce3a5ae392c98766ea6f93273d289bdf06ef02cc352e1f6fe65d34b7f48cd341c843e59b56661f842ac24e7dc36a4ec19173f59dcf7222bb7ab507b1817f71e057ba795735dd08559dc23c2f6dcc595494d0ec985e4e0e16b36abcdec83e3142896f8c2a937fbe1583849af6c8991f8f90941a4c7718ff7cd823101eb86ad64e7cfcdf86006db603cc08e599e1fd346c63b52ce4dfe7972d36b8eacdb4cf3de351ca7c719f648ecbbf1c5cb8d841f5736f7ae8ff45a372a1488be92ee7b3d091fbca22167b06d248410f358a335af128bbd7e02ed70ae91e0fb5f70d06333abdcf575bef416f3d30e2b3aff4845e08ece9ac509a5fd2cbf9a1283863f66a630e6588dc26af9eaf5f18e589f3ffad203657383b778639a24dd632b939327767cd1b852a954f63b5bb35487a597210cfed59dcad0a28ab1a551e1ecc2ef0a79e22dfb0714b0b50aaf95545b5f45cb4c4bc812d4f624bed926bb49c22ccf50cdbef9cce150b74b9963bfe91f18d2a35201d4976d9a2ecb67b156fabd49ba72944325f7517d909fc1824ae8f8db34c34ab34a0ea590150beb1561282ec26cf4943c5e629bbc78293643d0f70cdb5c7990ee3539cb8fcfe61cab75a36d0f7c099c632edda2e9fd10da7aabf33a2872fe1c5ea6c5d6d50b60a637efb9121bb12e74efcd29da98bac98a3b168b34fc997c305a938c3ff610752e339555fb6910f33b67eebc6bd2811bad1b3f9995a6c82fa3da88851f9e1ccef0c0996be05126b2e2ea36c08ad3cebb97f6ead4f8f38d7496db2975d53048d70042cf4f37ee86ce05f4a03e0c335dcdd9f6d9f782c63d43c927a9dbbe19971899642c654c4cac47f615fd74618648453816a93bc490d061ac4c086af4a517d2c7356ccc1b5bf762f9973297ab9fd4a8b8cd8871b96af579cb28f26dba71df41137d2b9090f75568abf45327f4de81103e183d6e8595c842eb4fe1d3225d4bbf72e77c18f3d83c3dcb6e76a92a01c186b3530a63b66f54b979c7d4c73bb141233cf99377d1b4dc73f8cec9137ba04fac6cea840adf8eb4cc509b0c63aac5aecc7cde30b6409eb4ca323312d79c44ac2494374dc7e7f0e31ebaeed587b7bf3d31f7de621906339f32d5f81e7eaf042b6ff8fa9bd5db397de237171374044ffc95ecf4a75a7a176adb8f3f3f38ce0c80bf1532c30bde67d89a046bb2c42389583c46cfd67acd78c3c8fdf51fb2848860da53ec5d2fe678d180f62a0ea89b4aa46f8a315bf1e5f6294eadef5eb7bf6de3e26fc9417e786d6841da076c2cd709ead9a93b28acd380207beedca590e19991a57f5ff33b621377c678fbcf7db962c91812735dafd90f46dd271fb13c80defd759b48032fda244c29e995831fee808c70caab4362385b13613b19f66f8edec0bbafd36139fe9faedd2ab9e7b477393b7351a5f9c6970f6ee081e3a7596e147ec7bf75a3f1d34d5fc9b27623272edfc6d56fb83b23e83398d60774511502c022e1b8f2a2ab57243a9e78e0687b67c80beec32b1124af16010377e8e3ea317f7708a65201cd11184cfea2eec9613cf331f92e7e597f4f42a3071edfbe8f646b7f08e10650edc137342511a93849fae3b10dfbccb74ffbe997fdaf37e068260c083c58f0edea347ee99d0ea311e05ad91467b7da4db5749e33f71f86ebfe89cb8a8b1d204bc1d655677d18529dc27880a6d884879e9c69af0c99d07f36f7e4cdf1ac67679eb8d9507ef3d72f1aa58d5502080f9cef4f7f8cca0e3d1f1332d118ce9df5ec7cb9db0b0ed5d55c770e64ec2658c6b2423ede1ff5b9d2c5681f1a8c12d181a3db4b2db4338690069ef823c77d184ac754230ddd59f97f507675362676f5c46db77c5de7aba36981643e804c409b1c68ddcac272858f60b357f6fb93ab636d2e096d95bad7b930761218fb128e755dd65bbe2d94d0aa51c12f6f7e0606e96a5f23d15500da64f8967959a01994280860e2ef7791a455afeb636451b8cd82721484cb29b1497fb8941f37442c6550d5a7ab815fe2c57bf4b13809ba39178bc880c8afc7d7f2db7cbf7bb931cde590555cda6bd6140949c45824327555e835bdd1f47332e8e1c4338e20bdd2287b7d09140601d3ca52c322efb8ea862e380ed460b2a2616c8eeb2d601f6785c102885639ba20396eb9aeabe235f6633b341a8333631c066de9f439474ac05b028baa00e5f96f8b8e511970c1ab54b2946efea21641b0eef8211c3f80a92f45c67b8b6d9aada1bbf3f6ff8ed0b6433cdc5e13a4e15d0eac3cc6633b4b577d198e632f188ea43841a5c35e814e2065d904152b240971035aaf486d764d66a9326b0bcf6373ce14aaa9eb15772ea21324b43a56890c92364bd976861b47b81aa7fc8bec3ea081eee2a0dc668f2e9583f7a8b21f040d909021423d8c007ea07f98a2b32e2ce0791011032f16ad8b9a8566ff771cd830980190104107dd03e32b36a75700f7c10b660fb1f587285d3788247728ce1f83451251b49ff4c8f5950be81d178e5140cd6aaf11f73ca748d0c8dfaae33001cc1e842ec5317f44710813ae320b60539c157bd00d7af00cf9eeb3258d5064842def46ff07f07c053255ba4cd88d0031b3d3dbbbc752566d2176b41534ad119fff9674ef15789b4af88e276d56dc5009c432f62c13428dd18fe5880f617a06dfe678b5525937b9a23494c4bd135b7b0c754508595d6d3c66c55ec9df1a22e0517775914e99204b502d17c2015a2ec20753c982f2808f8ff26bdef879a331485381786e05e64828b00441b166578ca880a334308ed0d288ff566a522822c2599b7875cb91d008bec503626ed87a29546245f767ce7991b714bdc7309af2128ab066f8ef0829db0134b7c20f1428ed8fe8db1616ec8ff739d7b208feec005ed0cb1f40b645f11422bad899603739e29aabcd8163e915c2804364d4c81e6b2d94db17ccb6230439249d63b304ba3791699c39ac0369e7241d10a47c82adee41c101c69b2c35d943069616b1c0c0607d97ec69ffb34e50810612269f561f93c336898852783a9f07c92199135c3e9e5fd53e5af094c32edf98d7a4d65a9c2df7884a386b8439e23e0641ebdbcbce3763f65d90f63b0aee9db03b51c6c22b94fce3c7dccceb50dddd800ef7fde8d5e4dfd3b030e0085a2be0eb0777fb25d3c6e2629b5871c79cc1ad68622a29826fa0fdee474493476a7d5023a5a1329da33160b1ca9bb5d1ca631a9d6ecff82b4b9ae0b92e10be6541aabb3454244bfcd6e258e9b4cb1b1601b4104c717327f3b5313d9051a8a975edf5587f4525a06ddb4f9cb1d8ec1f495c9ae0474b05a4b8d02dc57078fe62030e0cef39fc5f9a4fe1e17350699308a11288fffe73b110e7472932fa8fa0a3d074f9fd0585df0c1b2d913efee75fa6554eb06688693c2c25ed4529afe6ebe0a330341910f351bc7671ef0181a0ffd48df872511c23dcb1aeb2cca390ed3ca70ebb46b457bbf87ffc9209ea606e81ba86e8733b10479cd5c67699f0fd9b004fe108ef57f36568fd745e479c62fe4b8ed8921cca23113c5b64f757b546242ce67d8b8c7f5f794aecda86724405f595e43c4b6017a10576e5f36aee655a76948633cc39dc614a1d0cf8d6ff6bca5e17f0a5269339ae1b345471d57b2c51dc6ac7812bf1a7b012cfae24b227c7c3fc3313e7d66e937b4a1f90555ec8c72b0912ce930a1f891453ecb70ba15bb3ff0310b8d44379764e2ced96db4d95a064f22b2fd603534d11a9875dda711e268dda299dad0ab6f24ae901de7152e275bc87cb56b74436c99e2abd0bdc05c9ef4da14bbaccde374dce2cb36c45817264de83ffd813f619432061622636a42aa7cb3ba43be96ad0aa56273d7d4fe3bb73f847476604a0383f169f2f21bd707e894adb53f02d8d89b9d1738ccea718c217d60a3307debe641569d1198430ee70b977920db8cfb810e03ddc9ba9db3b227b713e13e71901fa4c1fcc4eef463cdb85fbdc20b3769c6b20fce5ddc83b7205322fd5e71c954596768360621098eea95a3562bab693be9f11e3c6f9f58cc918442c0cb349e0e0a4866126e80b52fcf2cc176f2c30058df8ed57dfb3ebdae702b5af7e36098a6674e3147f6c696a9ed17365594a098ee82a85791bbbfa5c05ffc80ed94cd60b4365ec13f35b307e08bc3ea34742acfe0fa821cff95811509b009acd2eb14636448858fcc88286127ee5a77c9ff3c0e736ae4de483cdb0bb10a4aa4c49953c50868236adeb0aaeec10c188fbcc56821b74731fa9136c76fd3e65a2a732a8c611dda07e7ee21dc2a45bd626027b8cdd8608ff35347850edc6965d5911ccba89340b070c0563e8b2f802258753ff9d8dbe2a88da6abe08d84fb0f9b7aa4fc84c61238815f6af49faa0f151092f14a4e4a5c3d1f2fedf85ffcaa880219a436ae85a6708bbeb24fcb392f0671ff766734ddf4666d260d74ad06a47498e4773ba5852feb96cbe59b9822356c3015c564143f74739f71136bbe0d8b3f8a7b8fa074d42f4dfd3f777528db8553253569f1fca07629288a348502ec91e03fe4a43e961753c795c5651da762ca83c04f293320b4cad39e406178e5da34bd213909bff95cc09836ee4ecca4c1d52d5656106cf1381fc6676958ae0298ef8044656e549cfea121cb62bb2ae3be1377fdde8fb7976dcdf91e0b9aa726cbbc9a6ff2f3a11fc1dc167614a2ffd1836688fc826bd1f8509b4d927f87d255548b171b78bf1bb31b579851c295e2196efdf031676026f7b1212bac995b01fb9e5945857581572fae4a692ebad8d0f928d7e22f01f8e97771dc13191203962214908da1482f4afe57fd1f9834cc5e2e0ad61dde479d5b47561aafb76a847787353751cd5658d530489c5518d3005a4babda4d44d4953c70442e7534534bd84f967f162939254290cad169ed6c16d05ac8396e1fbee5e6935d0e7f496d9f8728e785a70e29988e62f9644797829eba57eb9c60f11fead1a2299eddff8826a606ced412820768bde5a702d10db06165e33b53149eb9ff1d315c828565702fbf9fadb16d6c167c141bcee7d70dd09d3973a799566c0f9f316b8152038e18c93f5e21202df61ea465ea89117a4896b3f40d5850cee00d6d446f3e0f7f919a24016453c1f27298c5c33c473491d46e4cace6d69d79e283f0e134f02bbb55861fe57bb99fff6f24b7225dcf6a0cee5c0d8c7e78567ed92ffb2d965cd6d6bf922cc3ff430a94609c90fa7e9e9e51f22a8410b7e99a9dc48365410f2f8860841fae712b21ac8a7427dfc00fe799d70e9dfee6098e80eba462b9fc3fc0be1b5c6f24c187a3b4228bbc5eb7e03e6fdeb57c0ce35509cccc01122b71488667a71337722d5e54479e314d6b1dc0e0a1a7a9f0813e753bbc7d473bc54eb5428827df711cd84cd772b06cb918fe187e861f9a05c00769a483981e1bbc8eabf31234f70899bf296e9fbce985efa00f9a48c68e286bdc1e820c775e5dff00d25d50552f5a14d96b596239fc1407aa884ab212e868284ae5bbc6c40aed157a7bc5c20362bb3a33f5671c4b42389c4462cf2270d067dfcb495ecdab07c66555d3c3be0dd1ea33515fcda702d679dd6cd29dd3edd045e1c4d055710d7c282580f56ee3f0a246128960b71d91f56f59f7b414bb1b20ef244cf0e662aebe3e3122fe5c716666019f266ddcc400cfda377f2c637018c2b5cffe0aa529fad242737120cd1e2de9d180bbc89280965151102a648176e577940d7e23fd06b489e07e33d7d85555992a0faccae1b0af37bbf4e1cafe82065c20fd0aeff70021de42b9b3ca96e270796015561c27216b04cd84b92720155f226334758f6c15293fdda860885bf5baad60a58bde249dc2e42e4529c2aad241833594abdc4431897fbca2887030293e62da098ba2d4d71e84f7790adb0c48a0e666d15b7d2f9b541ac81f735c149ad1ef3ac56cd9ffb4cbc5a05a68eb2f5bde9512bee3f72d9629730c7f24ef6a79f126a75cf69a0fb3c0e9c07d3a17c84466016dbb72e2deaf588f39b2e245f75f1d8abb4986701dcbea2c6c7203e422768bdcb5c652e98761f188fda93d6410e334cbbcee016ee13e572e072ffaea04281fcb62117d70d595f3b9f51f7e1778205077f8ba541991ae94a8642677ed17141e02847d9b72b99cc7bc0bad3109f06434e469ebb393c77f529e21f54c71bcfe804b3b7797f9b292d02dcfe40d96eae078dd1e5e9fb30d8b6e265f61a5df98992c879284dc37d9d118dd1bc13b265c50ae14b5b20abbc5722de00e7ff0e0a53411d0fe517279954c34231229599899eeea55ab41fc268aa10291e8cba9a94f58a5d7d6ca82b293d35ce90e22262e2d26c8ba6686a962863da915bf044eee622085fdc9c8ad428ea76b29466d7d6e60c1cd8b5ae73d306da810a76795ef4d2e8144f1818c11034565b1a821e70da25379ab49b7365f519d1daac6ec3df3493ded0fbdfd83b20a8bedde03b757969b6d2bb5bca2a9aa05690649b88cf436c3061281ee83c77d89f63af24906b505ae01cfd8c88e631f4eb93e9dfd4ad8c03d75ac531789b540cac177616dd2aa4b849eff296b87f3824563dcc390af78bca69fe5e895a8280eb6a7d4ad25b2eb0e8a5facf483b8253e690a220ff5402f1293c308ce1ab136c3f56b670259e5de2e293730b380cfeaa08c851140cda837656c65f418b61a6b74e5faa2272969d02de0627965245f849f4b5fdc8303d34fbba4536107cc91fe40e5d68c47f81ab87f8307a808f72d63e2aba47e308921745e0085abdc82f2ac7a6cf8ab3c02828add28995b51ec87ffec35dd56994ff5905183e6bd4197849dead1a140af3eb8b615ad54b827962a2bbf828c7a0b4b1dba003d7473f27906ce42054ca9df00f37edd35886dcd4bf0d4b206dd08a3a46d58be7e30b25240568ad142a98953821ddc60713cb76237f8a599a12e7a4360a6745534c19c5be817244299e52a56ff5701ef081b5990b5f04a780361fe582122147121ee2341183035a15250dee83895d9a4c5cacfc62c5ffad10a4b6844c195fe0df22d8d7f55bbf5c59a42f3c4ac9b5e73ee02c0b062d3690ea22725497648bc8986ebbeb48b1a2f03f7b4658aab28cde4205fe122e848687ded1946fbb238265fcb9da4558859cee26fa1ed9e4c1d799b0ef2b6aeb703fbd138d60b545d3331f2404e2a669cb3eb54fd845f90e6272e167518403059acab5684521275859b82c91cadf5bf5dfded690d5ed46933a3be70c7456c1e0c2b28423419e2a8ef778ae421a43e981af282745f03cffb5661e171507bd4b9b2a7d1a3cfd977596e21b85d83d2981681c0672855241d14227b9148da55f253e4f9ac4a57918546fd29b66fcb564a14a183cc1aa0bd72b438d5b067aaf4d51e24ca0a1688cd5700d225dc4624802392f8cec372c9bf2fa038b6ec32ea02ede366d7186f82896b066586266fc05f368fd611fd17a1b70594cac9e872285696dc6892d644e4b004ee2fae206edfe8b26c31fdeb74f18e2878489035ebfd1bf432b5cd79e7fef14c127c4bd0d064739c146e7cfb3c2413a864435686497e91d782d39aa8b6c0a19375a438d57507d06a06fb03c358e7be3afe3bfa562af72d07a328ae21d3f6a4ea8ef87053ef5903d21414c180b6933a8877de4ee701a54809321b3fd63ffeae06f8f76f1f321a85a14b21bbaac5c162177979e347de2a51f45ea5ba932e12d45459205531a44b943278e470b3c38e28c08d676812565029f12d537cf1a62cda5ed04d32a7a940b8ac894c8a3220f22830aa35ee57088d51e83be8c77be74d9c7ea8938a0bd31251274b5085e0a8bb73f8be0ebad9125e4ad70d65b0227051ade824c65b6bd25b88732762b0111f4ce4b9541551114f2116456023503f4c043a45126880c5b3d54c643fc48999bd4899d70a5234b42fb58f6ac63c8f14e8d34fb0be616a61bee3e9495b6dad14c357624d05922a140b423b45c1c7217cef1e41dc1133d503381331dc6def2d430b6ba39ca86a46a7f1fa135714ad87ffd2ef10bbe97ae30fd3c870bdf7100e35e2542656dddab44e05a31c21097afe2d3e7cd182f86dc3e717069c6ee7cb76818661db39bd5f1bca83e5494b8342a7be79b7b03ed9449c1571fe7a847e5a616bbf105cba6d36baca5cc178c836c5dedd9a9722282b4e62aa2e66c5567d86106359967bba00394c75db694e0707c82391a5d6cc63a507eb10aa5cdfc3c2ee70e2796a8618212e3d1c41286eb9773f4a9d8493a4b0bb75154308b21e83834e05a9a0c67ce602e5d7d22dd19f334f5e9aeacd66758ac95f8e09038b2c0764611e4eb5b82dae8ef382b79cf8f72b50a2484a7c22710ebdacbbc0bc75dda54b024508436f664c6c7040814b71ffbe97e8430dc53da455ac347766a2b948de1cbaa0e21ac0d0d56dd09df9f27c9f567bcccc9d9a1c935fed88672b41b23bbfb4ee0fdb9f8db74b77244b11c8e62d7db08b3a2e21d629db78b6907baf8fc9281ea6c7c50a9515b2606e6c861dd8bf94b9d11fa11f6a2b300ff63ae268dabd58069c661b897492b864d3567324514ad1fc06df68260f5c52ecd50d54d113d7479f3ca4b44ff6ada79642fe93a6f9f8f2876fd48c5691b268b1cf2a552a7f4f7ac2b17605bb02e70643c44e87669a3f34312af97fe95bd1a7e9e4576c35eb8152b4fab3d60ba2186652fd8b24bd3e55766ea0f5fd31086d5cecac0038ce4113baf855ebb531c493c515991552e48ec816236c82689d99a8b1b5fbe6e2ba8e4dd6fa2a7529be0522f1280a9a68abc4870eec33dc8127961eadc8ed37e4c3fb3cdd6aa9d7069e38fd175bd648dea3966bdeff14bf66fde04f2707e093ab39277f8382eaf3a8601fae4de58ba20cf6fc265e03d2893de26ab55f6008a84a964fac6278bb7a68c9dface1373c40e1ec8338db791a1e900398077c02a6acb7de47289e8cffb3502e75eaf9b0ae028cc09a707c84f7abcba1a87a19f92ab328115b878e2bb854b17f2ec8229c1ca7882e98b46ce2e5cd83a1be21d829b2d522118ef718056ae6e2356c9517ffa52fa8fff1adceb30e01bcdb831e1650ba4826d0a58989aeae1b8ba0efaebc1fab447a7c8e51748b2f09dde2b4de1e68a82a61632a40c538664e2d7680e07f0750b587080474f17e596e58e72cd99f8f8fcbac66a9c90a89d5dbcbe3aad676f708f5de5723d06851cbc8b110118aa8e08f155b5499ef19ca0a8e7f4d920d5d0c11fe60c19ad8357a141620799d376951b3aab4259721129038aa0f72110622cee0becd734b765e44af6efb2795bf6723173d9e066e3bd5f8579dd22b44fb6183635661a7b7946fdd67cf8033efb2ce487f11ced3a2ed07e4b99244350a6e83821973769f9a9021a4f11f97125f6483abdbf98a470967004fde021e818bb7edffa28a4b70f68662e96a91d482c77787c40126e9b09ea36c1bf78acb7f73ec2e817a1a8a8004b4e0ab5df68bd68ef5030cddd997acee106d9756b7c73bbcc8d25facb87a6973c1e22218c3f19fcbbce6960a8d38062f029582a78b74615c88b3d7f7ec9b4f6f2fc1eb101b7ab2459a847d789a081c6dfd06b1cc651c621cd88c2666ae0fcfbd9052ea5e6335cf5eed05f8cf7f442e2cc8b3bdbb24e3066afab50d49429ce5381b198dacec81c38280c10e37a3dadf6954e2488d6bcffe8a12332200a4fad9637464b5a1dee1505bf5428ce2ec80d174289018600a52913cb4bb4cbe5de5b2d0a7518fc2d88d258c8e7ea4bc221f7688ab784640a61aedaa6ad79f7919616d8bd92c5fbe78748ca7545ff8ea5fbf46a5554a63dfd88068750c6eabbdc2cc1269b416293e0c92a154adb6689e6dc218dc75d084990339e108e09caf6f661c84214c4a5b057fb08a518e15b5a42d7576e23407e8098aa45b19d5dc87f9e486a5b757101fabf2412d48ab90bd5450638297ab1f21701e2846812ad3bd6c8c66f367c8d9b05177d8db5109876124c55268d0f3d59e15d569727cc2bd8856308254b9cb6250df4e65d5f4b4d096b6b837a450bad04cbf5bf91e6c88dd1686ea84709e01067c227d1e5df6bd4da31fce9ebf760d712a83367b5d7d6cafabad85c646c94e4b61f9256561381e12c198f7c84f85c51f98e7dcf25d5abbfa9ba6333ea2be1330b3fc2e7b3a7567d3d85f4a36da772e8032527596cdebd076ab2f4f9ae353fd7bf1c222d7d9cdccd079fea4e99a44f8655155b7518dc8b8484c74e693d249af3c4b80b01f68c2a64bffc5cecb8d23be667d2b605e3f0a47465701b47fc7971e0c8c5d0ccc7bd15a5ea98d06ba30a7cc5556b3770947e8850b1ff51d04dfd8da1e5cc57170ccc1512a13b0e9049bfbfcb123e4d34bae96f7538ff678ded58c235ad47f9ac76258495eda5c17b92e7e4b6e7f417183f160148c7683ad5f59f6f8bd919927ef14b5155cd3b25cd39d758b11120043d1bb94fa2d2787963635cc470e309770efdd15d80ef3118d0411106c39f7957937758ec64e1b64205d509d6f7f5afce92396f30f24df294d2ad8febdf58abbe3dba55e3430ea31561ad97076932b69edaf2e9eba4ca7ed15246a6fd0ebe96bf8782cc6f97ae7df670368a144860f57dd96398cf1133b163f9d76286b2474c5cf310ee250e81fb38288bc35f9a1decf80a17dee6c4ccde5758139dcdd63165d3ec0713eac86e59cb4d0e2a16eaffaa0f210d109b4a98aaf704dffe733540289aa2628979d7a2a40c70040fccec745d30edd99eac481da153a266ecc8bcc2a65f83edcb4ba4174aa6909e016835e491a0fa671b36282a83c6f3bc809012ff5a12ffa79b7fd79af2373f0c91fc108ddfaab3be519fa59c28827c7901211cdbc0f00cf4fe04cfea8b1b339987308a209513717962d278bee59a37d1598207356cb1e659fc0048480253d5d51a5962bee3b7c77f76702da47b9be5c8e46a96941ae43a832b7c9418fd371429e7f4bebaccefc2b272f35e7ed666761dbb9f8ebd2b6557db75a2540995f03b3cabf406adabeb4db79dee7d86f63adafe6e4d4ae49789d0b761c75cd9f6447df5f77b82d461fe3b318f0ba74fdb514d3e15bd0dce5e8be50e98dbf8ede829c73628c4759fda43aba8ec50dd5f2b3f0a9bf34ae76bd708f6749b425ffe361b76007e172a247bef5fe1c29d72dc93436e82da572b154fae7c4abf75afa68d8d053f65e13d92f17c52ca3ec72d762ee542e31f85588dafa7d87eb6d39720bf458effdc6f4260febe0cd2ebf56ad09459820287c212d05602b3c9297bf8656c44766f670d5f2e4183889a50a6badcf8e9d39cd1bb9a3f0460884551db00137cce7ef9d1faf0c00cfb3f99accd0f9a3d342526fc0f
| |
1 | 19,499,962 |
0d7c0852a0115c5e87c96c327309e46164442a20467f4fc3b02cbb89ff7c3035
|
f9c1acea334fa2d564d647fe696b83ac4bcd233756619c5f25c60c80dffeeb07
|
d4b69e8d62c880e9dd55d419d5e07435c3538342
|
1f98431c8ad98523631ae4a59f267346ea31f984
|
3902428a74a08a91e2cb2fd834de75e69974fe67
|
6101606040523480156200001257600080fd5b503060601b60805260408051630890357360e41b81529051600091339163890357309160048082019260a092909190829003018186803b1580156200005657600080fd5b505afa1580156200006b573d6000803e3d6000fd5b505050506040513d60a08110156200008257600080fd5b508051602080830151604084015160608086015160809096015160e896871b6001600160e81b0319166101005291811b6001600160601b031990811660e05292811b831660c0529390931b1660a052600282810b900b90921b610120529150620000f79082906200010f811b62002b8417901c565b60801b6001600160801b03191661014052506200017d565b60008082600281900b620d89e719816200012557fe5b05029050600083600281900b620d89e8816200013d57fe5b0502905060008460020b83830360020b816200015557fe5b0560010190508062ffffff166001600160801b038016816200017357fe5b0495945050505050565b60805160601c60a05160601c60c05160601c60e05160601c6101005160e81c6101205160e81c6101405160801c61567e6200024a60003980611fee5280614b5f5280614b96525080610c0052806128fd5280614bca5280614bfc525080610cef52806119cb5280611a0252806129455250806111c75280611a855280611ef4528061244452806129215280613e6b5250806108d252806112f55280611a545280611e8e52806123be5280613d2252508061207b528061227d52806128d9525080612bfb525061567e6000f3fe608060405234801561001057600080fd5b50600436106101ae5760003560e01c806370cf754a116100ee578063c45a015511610097578063ddca3f4311610071578063ddca3f4314610800578063f305839914610820578063f30dba9314610828578063f637731d146108aa576101ae565b8063c45a0155146107d1578063d0c93a7c146107d9578063d21220a7146107f8576101ae565b8063883bdbfd116100c8578063883bdbfd14610633578063a34123a71461073c578063a38807f214610776576101ae565b806370cf754a146105c65780638206a4d1146105ce57806385b66729146105f6576101ae565b80633850c7bd1161015b578063490e6cbc11610135578063490e6cbc146104705780634f1eb3d8146104fc578063514ea4bf1461054d5780635339c296146105a6576101ae565b80633850c7bd1461035b5780633c8a7d8d146103b45780634614131914610456576101ae565b80631ad8b03b1161018c5780631ad8b03b146102aa578063252c09d7146102e157806332148f6714610338576101ae565b80630dfe1681146101b3578063128acb08146101d75780631a68650214610286575b600080fd5b6101bb6108d0565b604080516001600160a01b039092168252519081900360200190f35b61026d600480360360a08110156101ed57600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a08101608082013564010000000081111561022e57600080fd5b82018360208201111561024057600080fd5b8035906020019184600183028401116401000000008311171561026257600080fd5b5090925090506108f4565b6040805192835260208301919091528051918290030190f35b61028e6114ad565b604080516001600160801b039092168252519081900360200190f35b6102b26114bc565b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102fe600480360360208110156102f757600080fd5b50356114d6565b6040805163ffffffff909516855260069390930b60208501526001600160a01b039091168383015215156060830152519081900360800190f35b6103596004803603602081101561034e57600080fd5b503561ffff1661151c565b005b610363611616565b604080516001600160a01b03909816885260029690960b602088015261ffff9485168787015292841660608701529216608085015260ff90911660a0840152151560c0830152519081900360e00190f35b61026d600480360360a08110156103ca57600080fd5b6001600160a01b03823516916020810135600290810b92604083013590910b916001600160801b036060820135169181019060a08101608082013564010000000081111561041757600080fd5b82018360208201111561042957600080fd5b8035906020019184600183028401116401000000008311171561044b57600080fd5b509092509050611666565b61045e611922565b60408051918252519081900360200190f35b6103596004803603608081101561048657600080fd5b6001600160a01b0382351691602081013591604082013591908101906080810160608201356401000000008111156104bd57600080fd5b8201836020820111156104cf57600080fd5b803590602001918460018302840111640100000000831117156104f157600080fd5b509092509050611928565b6102b2600480360360a081101561051257600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b0360608201358116916080013516611d83565b61056a6004803603602081101561056357600080fd5b5035611f9d565b604080516001600160801b0396871681526020810195909552848101939093529084166060840152909216608082015290519081900360a00190f35b61045e600480360360208110156105bc57600080fd5b503560010b611fda565b61028e611fec565b610359600480360360408110156105e457600080fd5b5060ff81358116916020013516612010565b6102b26004803603606081101561060c57600080fd5b506001600160a01b03813516906001600160801b036020820135811691604001351661220f565b6106a36004803603602081101561064957600080fd5b81019060208101813564010000000081111561066457600080fd5b82018360208201111561067657600080fd5b8035906020019184602083028401116401000000008311171561069857600080fd5b5090925090506124dc565b604051808060200180602001838103835285818151815260200191508051906020019060200280838360005b838110156106e75781810151838201526020016106cf565b50505050905001838103825284818151815260200191508051906020019060200280838360005b8381101561072657818101518382015260200161070e565b5050505090500194505050505060405180910390f35b61026d6004803603606081101561075257600080fd5b508035600290810b91602081013590910b90604001356001600160801b0316612569565b6107a06004803603604081101561078c57600080fd5b508035600290810b9160200135900b6126e0565b6040805160069490940b84526001600160a01b03909216602084015263ffffffff1682820152519081900360600190f35b6101bb6128d7565b6107e16128fb565b6040805160029290920b8252519081900360200190f35b6101bb61291f565b610808612943565b6040805162ffffff9092168252519081900360200190f35b61045e612967565b6108486004803603602081101561083e57600080fd5b503560020b61296d565b604080516001600160801b039099168952600f9790970b602089015287870195909552606087019390935260069190910b60808601526001600160a01b031660a085015263ffffffff1660c0840152151560e083015251908190036101000190f35b610359600480360360208110156108c057600080fd5b50356001600160a01b03166129db565b7f000000000000000000000000000000000000000000000000000000000000000081565b6000806108ff612bf0565b85610936576040805162461bcd60e51b8152602060048201526002602482015261415360f01b604482015290519081900360640190fd5b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526109ef576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b87610a3a5780600001516001600160a01b0316866001600160a01b0316118015610a35575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038716105b610a6c565b80600001516001600160a01b0316866001600160a01b0316108015610a6c57506401000276a36001600160a01b038716115b610aa3576040805162461bcd60e51b815260206004820152600360248201526214d41360ea1b604482015290519081900360640190fd5b6000805460ff60f01b191681556040805160c08101909152808a610ad25760048460a0015160ff16901c610ae5565b60108460a0015160ff1681610ae357fe5b065b60ff1681526004546001600160801b03166020820152604001610b06612c27565b63ffffffff168152602001600060060b815260200160006001600160a01b031681526020016000151581525090506000808913905060006040518060e001604052808b81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018c610b8257600254610b86565b6001545b815260200160006001600160801b0316815260200184602001516001600160801b031681525090505b805115801590610bd55750886001600160a01b031681604001516001600160a01b031614155b15610f9f57610be261560e565b60408201516001600160a01b031681526060820151610c25906006907f00000000000000000000000000000000000000000000000000000000000000008f612c2b565b15156040830152600290810b810b60208301819052620d89e719910b1215610c5657620d89e7196020820152610c75565b6020810151620d89e860029190910b1315610c7557620d89e860208201525b610c828160200151612d6d565b6001600160a01b031660608201526040820151610d13908d610cbc578b6001600160a01b031683606001516001600160a01b031611610cd6565b8b6001600160a01b031683606001516001600160a01b0316105b610ce4578260600151610ce6565b8b5b60c085015185517f000000000000000000000000000000000000000000000000000000000000000061309f565b60c085015260a084015260808301526001600160a01b031660408301528215610d7557610d498160c00151826080015101613291565b825103825260a0810151610d6b90610d6090613291565b6020840151906132a7565b6020830152610db0565b610d828160a00151613291565b825101825260c08101516080820151610daa91610d9f9101613291565b6020840151906132c3565b60208301525b835160ff1615610df6576000846000015160ff168260c0015181610dd057fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610e3557610e298160c00151600160801b8460c001516001600160801b03166132d9565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610f5e57806040015115610f35578360a00151610ebf57610e9d846040015160008760200151886040015188602001518a606001516008613389909695949392919063ffffffff16565b6001600160a01b03166080860152600690810b900b6060850152600160a08501525b6000610f0b82602001518e610ed657600154610edc565b84608001515b8f610eeb578560800151610eef565b6002545b608089015160608a015160408b0151600595949392919061351c565b90508c15610f17576000035b610f258360c00151826135ef565b6001600160801b031660c0840152505b8b610f44578060200151610f4d565b60018160200151035b600290810b900b6060830152610f99565b80600001516001600160a01b031682604001516001600160a01b031614610f9957610f8c82604001516136a5565b600290810b900b60608301525b50610baf565b836020015160020b816060015160020b1461107a57600080610fed86604001518660400151886020015188602001518a606001518b6080015160086139d1909695949392919063ffffffff16565b604085015160608601516000805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b93909316929092029190911773ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03909116179055506110ac9050565b60408101516000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039092169190911790555b8060c001516001600160801b031683602001516001600160801b0316146110f25760c0810151600480546001600160801b0319166001600160801b039092169190911790555b8a1561114257608081015160015560a08101516001600160801b03161561113d5760a0810151600380546001600160801b031981166001600160801b03918216909301169190911790555b611188565b608081015160025560a08101516001600160801b0316156111885760a0810151600380546001600160801b03808216600160801b92839004821690940116029190911790555b8115158b1515146111a157602081015181518b036111ae565b80600001518a0381602001515b90965094508a156112e75760008512156111f0576111f07f00000000000000000000000000000000000000000000000000000000000000008d87600003613b86565b60006111fa613cd4565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b15801561127e57600080fd5b505af1158015611292573d6000803e3d6000fd5b5050505061129e613cd4565b6112a88289613e0d565b11156112e1576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b50611411565b600086121561131e5761131e7f00000000000000000000000000000000000000000000000000000000000000008d88600003613b86565b6000611328613e1d565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506113cc613e1d565b6113d68288613e0d565b111561140f576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b505b60408082015160c083015160608085015184518b8152602081018b90526001600160a01b03948516818701526001600160801b039093169183019190915260020b60808201529151908e169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679181900360a00190a350506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b6004546001600160801b031681565b6003546001600160801b0380821691600160801b90041682565b60088161ffff81106114e757600080fd5b015463ffffffff81169150640100000000810460060b90600160581b81046001600160a01b031690600160f81b900460ff1684565b600054600160f01b900460ff16611560576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611575612bf0565b60008054600160d81b900461ffff169061159160088385613eb5565b6000805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115fe576040805161ffff80851682528316602082015281517fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a929181900390910190a15b50506000805460ff60f01b1916600160f01b17905550565b6000546001600160a01b03811690600160a01b810460020b9061ffff600160b81b8204811691600160c81b8104821691600160d81b8204169060ff600160e81b8204811691600160f01b90041687565b600080548190600160f01b900460ff166116ad576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b191690556001600160801b0385166116cd57600080fd5b60008061171b60405180608001604052808c6001600160a01b031681526020018b60020b81526020018a60020b81526020016117118a6001600160801b0316613f58565b600f0b9052613f69565b9250925050819350809250600080600086111561173d5761173a613cd4565b91505b841561174e5761174b613e1d565b90505b336001600160a01b031663d348799787878b8b6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156117d057600080fd5b505af11580156117e4573d6000803e3d6000fd5b50505050600086111561183b576117f9613cd4565b6118038388613e0d565b111561183b576040805162461bcd60e51b815260206004820152600260248201526104d360f41b604482015290519081900360640190fd5b841561188b57611849613e1d565b6118538287613e0d565b111561188b576040805162461bcd60e51b81526020600482015260026024820152614d3160f01b604482015290519081900360640190fd5b8960020b8b60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8b8b60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a450506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b60025481565b600054600160f01b900460ff1661196c576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611981612bf0565b6004546001600160801b0316806119c3576040805162461bcd60e51b81526020600482015260016024820152601360fa1b604482015290519081900360640190fd5b60006119f8867f000000000000000000000000000000000000000000000000000000000000000062ffffff16620f42406141a9565b90506000611a2f867f000000000000000000000000000000000000000000000000000000000000000062ffffff16620f42406141a9565b90506000611a3b613cd4565b90506000611a47613e1d565b90508815611a7a57611a7a7f00000000000000000000000000000000000000000000000000000000000000008b8b613b86565b8715611aab57611aab7f00000000000000000000000000000000000000000000000000000000000000008b8a613b86565b336001600160a01b031663e9cbafb085858a8a6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b158015611b2d57600080fd5b505af1158015611b41573d6000803e3d6000fd5b505050506000611b4f613cd4565b90506000611b5b613e1d565b905081611b688588613e0d565b1115611ba0576040805162461bcd60e51b8152602060048201526002602482015261046360f41b604482015290519081900360640190fd5b80611bab8487613e0d565b1115611be3576040805162461bcd60e51b8152602060048201526002602482015261463160f01b604482015290519081900360640190fd5b8382038382038115611c725760008054600160e81b9004600f16908115611c16578160ff168481611c1057fe5b04611c19565b60005b90506001600160801b03811615611c4c57600380546001600160801b038082168401166001600160801b03199091161790555b611c66818503600160801b8d6001600160801b03166132d9565b60018054909101905550505b8015611cfd5760008054600160e81b900460041c600f16908115611ca2578160ff168381611c9c57fe5b04611ca5565b60005b90506001600160801b03811615611cd757600380546001600160801b03600160801b8083048216850182160291161790555b611cf1818403600160801b8d6001600160801b03166132d9565b60028054909101905550505b8d6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338f8f86866040518085815260200184815260200183815260200182815260200194505050505060405180910390a350506000805460ff60f01b1916600160f01b179055505050505050505050505050565b600080548190600160f01b900460ff16611dca576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19168155611de460073389896141e3565b60038101549091506001600160801b0390811690861611611e055784611e14565b60038101546001600160801b03165b60038201549093506001600160801b03600160801b909104811690851611611e3c5783611e52565b6003810154600160801b90046001600160801b03165b91506001600160801b03831615611eb7576003810180546001600160801b031981166001600160801b03918216869003821617909155611eb7907f0000000000000000000000000000000000000000000000000000000000000000908a908616613b86565b6001600160801b03821615611f1d576003810180546001600160801b03600160801b808304821686900382160291811691909117909155611f1d907f0000000000000000000000000000000000000000000000000000000000000000908a908516613b86565b604080516001600160a01b038a1681526001600160801b0380861660208301528416818301529051600288810b92908a900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a4506000805460ff60f01b1916600160f01b17905590969095509350505050565b60076020526000908152604090208054600182015460028301546003909301546001600160801b0392831693919281811691600160801b90041685565b60066020526000908152604090205481565b7f000000000000000000000000000000000000000000000000000000000000000081565b600054600160f01b900460ff16612054576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691638da5cb5b916004808301926020929190829003018186803b1580156120c157600080fd5b505afa1580156120d5573d6000803e3d6000fd5b505050506040513d60208110156120eb57600080fd5b50516001600160a01b0316331461210157600080fd5b60ff82161580612124575060048260ff16101580156121245750600a8260ff1611155b801561214e575060ff8116158061214e575060048160ff161015801561214e5750600a8160ff1611155b61215757600080fd5b60008054610ff0600484901b16840160ff908116600160e81b9081027fffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff841617909355919004167f973d8d92bb299f4af6ce49b52a8adb85ae46b9f214c4c4fc06ac77401237b1336010826040805160ff9390920683168252600f600486901c16602083015286831682820152918516606082015290519081900360800190a150506000805460ff60f01b1916600160f01b17905550565b600080548190600160f01b900460ff16612256576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691638da5cb5b916004808301926020929190829003018186803b1580156122c357600080fd5b505afa1580156122d7573d6000803e3d6000fd5b505050506040513d60208110156122ed57600080fd5b50516001600160a01b0316331461230357600080fd5b6003546001600160801b039081169085161161231f578361232c565b6003546001600160801b03165b6003549092506001600160801b03600160801b9091048116908416116123525782612366565b600354600160801b90046001600160801b03165b90506001600160801b038216156123e7576003546001600160801b038381169116141561239557600019909101905b600380546001600160801b031981166001600160801b039182168590038216179091556123e7907f00000000000000000000000000000000000000000000000000000000000000009087908516613b86565b6001600160801b0381161561246d576003546001600160801b03828116600160801b90920416141561241857600019015b600380546001600160801b03600160801b80830482168590038216029181169190911790915561246d907f00000000000000000000000000000000000000000000000000000000000000009087908416613b86565b604080516001600160801b0380851682528316602082015281516001600160a01b0388169233927f596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151929081900390910190a36000805460ff60f01b1916600160f01b1790559094909350915050565b6060806124e7612bf0565b61255e6124f2612c27565b858580806020026020016040519081016040528093929190818152602001838360200280828437600092018290525054600454600896959450600160a01b820460020b935061ffff600160b81b8304811693506001600160801b0390911691600160c81b900416614247565b915091509250929050565b600080548190600160f01b900460ff166125b0576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916815560408051608081018252338152600288810b602083015287900b918101919091528190819061260990606081016125fc6001600160801b038a16613f58565b600003600f0b9052613f69565b925092509250816000039450806000039350600085118061262a5750600084115b15612669576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b604080516001600160801b0388168152602081018790528082018690529051600289810b92908b900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a450506000805460ff60f01b1916600160f01b179055509094909350915050565b60008060006126ed612bf0565b6126f785856143a1565b600285810b810b60009081526005602052604080822087840b90930b825281206003830154600681900b9367010000000000000082046001600160a01b0316928492600160d81b810463ffffffff169284929091600160f81b900460ff168061275f57600080fd5b6003820154600681900b985067010000000000000081046001600160a01b03169650600160d81b810463ffffffff169450600160f81b900460ff16806127a457600080fd5b50506040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b810b6020840181905261ffff600160b81b8404811695850195909552600160c81b830485166060850152600160d81b8304909416608084015260ff600160e81b8304811660a0850152600160f01b909204909116151560c08301529093508e810b91900b1215905061284d575093909403965090039350900390506128d0565b8a60020b816020015160020b12156128c1576000612869612c27565b602083015160408401516004546060860151939450600093849361289f936008938893879392916001600160801b031690613389565b9a9003989098039b5050949096039290920396509091030392506128d0915050565b50949093039650039350900390505b9250925092565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b60015481565b60056020526000908152604090208054600182015460028301546003909301546001600160801b03831693600160801b909304600f0b9290600681900b9067010000000000000081046001600160a01b031690600160d81b810463ffffffff1690600160f81b900460ff1688565b6000546001600160a01b031615612a1e576040805162461bcd60e51b8152602060048201526002602482015261414960f01b604482015290519081900360640190fd5b6000612a29826136a5565b9050600080612a41612a39612c27565b60089061446a565b6040805160e0810182526001600160a01b038816808252600288810b6020808501829052600085870181905261ffff898116606088018190529089166080880181905260a08801839052600160c0909801979097528154600160f01b73ffffffffffffffffffffffffffffffffffffffff19909116871762ffffff60a01b1916600160a01b62ffffff9787900b9790971696909602959095177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9091021761ffff60d81b1916600160d81b909602959095177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1692909217909355835191825281019190915281519395509193507f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9592918290030190a150505050565b60008082600281900b620d89e71981612b9957fe5b05029050600083600281900b620d89e881612bb057fe5b0502905060008460020b83830360020b81612bc757fe5b0560010190508062ffffff166001600160801b03801681612be457fe5b0493505050505b919050565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612c2557600080fd5b565b4290565b60008060008460020b8660020b81612c3f57fe5b05905060008660020b128015612c6657508460020b8660020b81612c5f57fe5b0760020b15155b15612c7057600019015b8315612ce557600080612c82836144b6565b600182810b810b600090815260208d9052604090205460ff83169190911b80016000190190811680151597509294509092509085612cc757888360ff16860302612cda565b88612cd1826144c8565b840360ff168603025b965050505050612d63565b600080612cf4836001016144b6565b91509150600060018260ff166001901b031990506000818b60008660010b60010b8152602001908152602001600020541690508060001415955085612d4657888360ff0360ff16866001010102612d5c565b8883612d5183614568565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b12612d84578260020b612d8c565b8260020b6000035b9050620d89e8811115612dca576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612dde57600160801b612df0565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e24576ffff97272373d413259a46990580e213a0260801c5b6004821615612e43576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e62576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e81576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612ea0576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612ebf576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ede576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612efe576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f1e576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f3e576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f5e576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f7e576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f9e576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612fbe576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fde576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612fff576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561301f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561303e576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561305b576b048a170391f7dc42444e8fa20260801c5b60008460020b131561307657806000198161307257fe5b0490505b64010000000081061561308a57600161308d565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906131245760006130d88989620f42400362ffffff16620f42406132d9565b9050826130f1576130ec8c8c8c6001614652565b6130fe565b6130fe8b8d8c60016146cd565b955085811061310f578a965061311e565b61311b8c8b838661478a565b96505b5061316e565b8161313b576131368b8b8b60006146cd565b613148565b6131488a8c8b6000614652565b935083886000031061315c5789955061316e565b61316b8b8a8a600003856147d6565b95505b6001600160a01b038a81169087161482156131d15780801561318d5750815b6131a35761319e878d8c60016146cd565b6131a5565b855b95508080156131b2575081155b6131c8576131c3878d8c6000614652565b6131ca565b845b945061321b565b8080156131db5750815b6131f1576131ec8c888c6001614652565b6131f3565b855b9550808015613200575081155b613216576132118c888c60006146cd565b613218565b845b94505b8115801561322b57508860000385115b15613237578860000394505b81801561325657508a6001600160a01b0316876001600160a01b031614155b15613265578589039350613282565b61327f868962ffffff168a620f42400362ffffff166141a9565b93505b50505095509550955095915050565b6000600160ff1b82106132a357600080fd5b5090565b808203828113156000831215146132bd57600080fd5b92915050565b818101828112156000831215146132bd57600080fd5b600080806000198587098686029250828110908390030390508061330f576000841161330457600080fd5b508290049050613382565b80841161331b57600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008063ffffffff8716613430576000898661ffff1661ffff81106133aa57fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a161461341c57613419818a8988614822565b90505b806020015181604001519250925050613510565b8688036000806134458c8c858c8c8c8c6148d2565b91509150816000015163ffffffff168363ffffffff161415613477578160200151826040015194509450505050613510565b805163ffffffff8481169116141561349f578060200151816040015194509450505050613510565b8151815160208085015190840151918390039286039163ffffffff80841692908516910360060b816134cd57fe5b05028460200151018263ffffffff168263ffffffff1686604001518660400151036001600160a01b031602816134ff57fe5b048560400151019650965050505050505b97509795505050505050565b600295860b860b60009081526020979097526040909620600181018054909503909455938301805490920390915560038201805463ffffffff600160d81b6001600160a01b036701000000000000008085048216909603169094027fffffffffff0000000000000000000000000000000000000000ffffffffffffff90921691909117600681810b90960390950b66ffffffffffffff1666ffffffffffffff199095169490941782810485169095039093160263ffffffff60d81b1990931692909217905554600160801b9004600f0b90565b60008082600f0b121561365457826001600160801b03168260000384039150816001600160801b03161061364f576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b6132bd565b826001600160801b03168284019150816001600160801b031610156132bd576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b038316108015906136e1575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613716576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106137b757607f810383901c91506137c1565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146139c257886001600160a01b03166139a682612d6d565b6001600160a01b031611156139bb57816139bd565b805b6139c4565b815b9998505050505050505050565b6000806000898961ffff1661ffff81106139e757fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff161515606083015290925089161415613a575788859250925050613510565b8461ffff168461ffff16118015613a7857506001850361ffff168961ffff16145b15613a8557839150613a89565b8491505b8161ffff168960010161ffff1681613a9d57fe5b069250613aac81898989614822565b8a8461ffff1661ffff8110613abd57fe5b825191018054602084015160408501516060909501511515600160f81b027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b03909616600160581b027fff0000000000000000000000000000000000000000ffffffffffffffffffffff60069390930b66ffffffffffffff16640100000000026affffffffffffff000000001963ffffffff90971663ffffffff199095169490941795909516929092171692909217929092161790555097509795505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c025780518252601f199092019160209182019101613be3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c64576040519150601f19603f3d011682016040523d82523d6000602084013e613c69565b606091505b5091509150818015613c97575080511580613c975750808060200190516020811015613c9457600080fd5b50515b613ccd576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b5050505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001693919290918291908083835b60208310613d6d5780518252601f199092019160209182019101613d4e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613dcd576040519150601f19603f3d011682016040523d82523d6000602084013e613dd2565b606091505b5091509150818015613de657506020815110155b613def57600080fd5b808060200190516020811015613e0457600080fd5b50519250505090565b808201828110156132bd57600080fd5b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016939192909182919080838360208310613d6d5780518252601f199092019160209182019101613d4e565b6000808361ffff1611613ef3576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b8261ffff168261ffff1611613f09575081613382565b825b8261ffff168161ffff161015613f4f576001858261ffff1661ffff8110613f2e57fe5b01805463ffffffff191663ffffffff92909216919091179055600101613f0b565b50909392505050565b80600f81900b8114612beb57600080fd5b6000806000613f76612bf0565b613f88846020015185604001516143a1565b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602080840182905261ffff600160b81b8404811685870152600160c81b84048116606080870191909152600160d81b8504909116608086015260ff600160e81b8504811660a0870152600160f01b909404909316151560c08501528851908901519489015192890151939461402c9491939092909190614acf565b93508460600151600f0b6000146141a157846020015160020b816020015160020b12156140815761407a6140638660200151612d6d565b6140708760400151612d6d565b8760600151614c84565b92506141a1565b846040015160020b816020015160020b12156141775760045460408201516001600160801b03909116906140d3906140b7612c27565b60208501516060860151608087015160089493929187916139d1565b6000805461ffff60c81b1916600160c81b61ffff938416021761ffff60b81b1916600160b81b939092169290920217905581516040870151614123919061411990612d6d565b8860600151614c84565b93506141416141358760200151612d6d565b83516060890151614cc8565b92506141518187606001516135ef565b600480546001600160801b0319166001600160801b0392909216919091179055506141a1565b61419e6141878660200151612d6d565b6141948760400151612d6d565b8760600151614cc8565b91505b509193909250565b60006141b68484846132d9565b9050600082806141c257fe5b84860911156133825760001981106141d957600080fd5b6001019392505050565b6040805160609490941b6bffffffffffffffffffffffff1916602080860191909152600293840b60e890811b60348701529290930b90911b60378401528051808403601a018152603a90930181528251928201929092206000908152929052902090565b60608060008361ffff1611614287576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b865167ffffffffffffffff8111801561429f57600080fd5b506040519080825280602002602001820160405280156142c9578160200160208202803683370190505b509150865167ffffffffffffffff811180156142e457600080fd5b5060405190808252806020026020018201604052801561430e578160200160208202803683370190505b50905060005b87518110156143945761433f8a8a8a848151811061432e57fe5b60200260200101518a8a8a8a613389565b84838151811061434b57fe5b6020026020010184848151811061435e57fe5b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b81525050508080600101915050614314565b5097509795505050505050565b8060020b8260020b126143e1576040805162461bcd60e51b8152602060048201526003602482015262544c5560e81b604482015290519081900360640190fd5b620d89e719600283900b1215614424576040805162461bcd60e51b8152602060048201526003602482015262544c4d60e81b604482015290519081900360640190fd5b620d89e8600282900b1315614466576040805162461bcd60e51b815260206004820152600360248201526254554d60e81b604482015290519081900360640190fd5b5050565b6040805160808101825263ffffffff9283168082526000602083018190529282019290925260016060909101819052835463ffffffff1916909117909116600160f81b17909155908190565b60020b600881901d9161010090910790565b60008082116144d657600080fd5b600160801b82106144e957608091821c91015b68010000000000000000821061450157604091821c91015b640100000000821061451557602091821c91015b62010000821061452757601091821c91015b610100821061453857600891821c91015b6010821061454857600491821c91015b6004821061455857600291821c91015b60028210612beb57600101919050565b600080821161457657600080fd5b5060ff6001600160801b0382161561459157607f1901614599565b608082901c91505b67ffffffffffffffff8216156145b257603f19016145ba565b604082901c91505b63ffffffff8216156145cf57601f19016145d7565b602082901c91505b61ffff8216156145ea57600f19016145f2565b601082901c91505b60ff821615614604576007190161460c565b600882901c91505b600f82161561461e5760031901614626565b600482901c91505b60038216156146385760011901614640565b600282901c91505b6001821615612beb5760001901919050565b6000836001600160a01b0316856001600160a01b03161115614672579293925b8161469f5761469a836001600160801b03168686036001600160a01b0316600160601b6132d9565b6146c2565b6146c2836001600160801b03168686036001600160a01b0316600160601b6141a9565b90505b949350505050565b6000836001600160a01b0316856001600160a01b031611156146ed579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661472957600080fd5b8361475957866001600160a01b031661474c8383896001600160a01b03166132d9565b8161475357fe5b0461477f565b61477f6147708383896001600160a01b03166141a9565b886001600160a01b0316614cf7565b979650505050505050565b600080856001600160a01b0316116147a157600080fd5b6000846001600160801b0316116147b757600080fd5b816147c95761469a8585856001614d02565b6146c28585856001614de3565b600080856001600160a01b0316116147ed57600080fd5b6000846001600160801b03161161480357600080fd5b816148155761469a8585856000614de3565b6146c28585856000614d02565b61482a61564a565b600085600001518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020016000856001600160801b03161161487e576001614880565b845b6001600160801b031673ffffffff00000000000000000000000000000000608085901b16816148ab57fe5b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b6148da61564a565b6148e261564a565b888561ffff1661ffff81106148f357fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff1615156060820152925061495890899089614ed8565b15614990578663ffffffff16826000015163ffffffff16141561497a57613510565b8161498783898988614822565b91509150613510565b888361ffff168660010161ffff16816149a557fe5b0661ffff1661ffff81106149b557fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909250614a6c57604080516080810182528a5463ffffffff811682526401000000008104600690810b810b900b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b614a7b88836000015189614ed8565b614ab2576040805162461bcd60e51b815260206004820152600360248201526213d31160ea1b604482015290519081900360640190fd5b614abf8989898887614f9b565b9150915097509795505050505050565b6000614ade60078787876141e3565b60015460025491925090600080600f87900b15614c24576000614aff612c27565b6000805460045492935090918291614b499160089186918591600160a01b810460020b9161ffff600160b81b83048116926001600160801b0390921691600160c81b900416613389565b9092509050614b8360058d8b8d8b8b87898b60007f000000000000000000000000000000000000000000000000000000000000000061513b565b9450614bba60058c8b8d8b8b87898b60017f000000000000000000000000000000000000000000000000000000000000000061513b565b93508415614bee57614bee60068d7f0000000000000000000000000000000000000000000000000000000000000000615325565b8315614c2057614c2060068c7f0000000000000000000000000000000000000000000000000000000000000000615325565b5050505b600080614c3660058c8c8b8a8a61538b565b9092509050614c47878a8484615437565b600089600f0b1215614c75578315614c6457614c6460058c6155cc565b8215614c7557614c7560058b6155cc565b50505050505095945050505050565b60008082600f0b12614caa57614ca5614ca085858560016146cd565b613291565b6146c5565b614cbd614ca085858560000360006146cd565b600003949350505050565b60008082600f0b12614ce457614ca5614ca08585856001614652565b614cbd614ca08585856000036000614652565b808204910615150190565b60008115614d755760006001600160a01b03841115614d3857614d3384600160601b876001600160801b03166132d9565b614d50565b6001600160801b038516606085901b81614d4e57fe5b045b9050614d6d614d686001600160a01b03881683613e0d565b6155f8565b9150506146c5565b60006001600160a01b03841115614da357614d9e84600160601b876001600160801b03166141a9565b614dba565b614dba606085901b6001600160801b038716614cf7565b905080866001600160a01b031611614dd157600080fd5b6001600160a01b0386160390506146c5565b600082614df15750836146c5565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b168215614e91576001600160a01b03861684810290858281614e3157fe5b041415614e6257818101828110614e6057614e5683896001600160a01b0316836141a9565b93505050506146c5565b505b614e8882614e83878a6001600160a01b03168681614e7c57fe5b0490613e0d565b614cf7565b925050506146c5565b6001600160a01b03861684810290858281614ea857fe5b04148015614eb557508082115b614ebe57600080fd5b808203614e56614d68846001600160a01b038b16846141a9565b60008363ffffffff168363ffffffff1611158015614f0257508363ffffffff168263ffffffff1611155b15614f1e578163ffffffff168363ffffffff1611159050613382565b60008463ffffffff168463ffffffff1611614f46578363ffffffff1664010000000001614f4e565b8363ffffffff165b64ffffffffff16905060008563ffffffff168463ffffffff1611614f7f578363ffffffff1664010000000001614f87565b8363ffffffff165b64ffffffffff169091111595945050505050565b614fa361564a565b614fab61564a565b60008361ffff168560010161ffff1681614fc157fe5b0661ffff169050600060018561ffff16830103905060005b506002818301048961ffff87168281614fee57fe5b0661ffff8110614ffa57fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290955061506557806001019250614fd9565b898661ffff16826001018161507657fe5b0661ffff811061508257fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094506000906150ed908b908b614ed8565b905080801561510657506151068a8a8760000151614ed8565b15615111575061512e565b8061512157600182039250615128565b8160010193505b50614fd9565b5050509550959350505050565b60028a810b900b600090815260208c90526040812080546001600160801b031682615166828d6135ef565b9050846001600160801b0316816001600160801b031611156151b4576040805162461bcd60e51b81526020600482015260026024820152614c4f60f01b604482015290519081900360640190fd5b6001600160801b03828116159082161581141594501561528a578c60020b8e60020b1361525a57600183018b9055600283018a90556003830180547fffffffffff0000000000000000000000000000000000000000ffffffffffffff166701000000000000006001600160a01b038c16021766ffffffffffffff191666ffffffffffffff60068b900b161763ffffffff60d81b1916600160d81b63ffffffff8a16021790555b6003830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b038216178355856152d35782546152ce906152c990600160801b9004600f90810b810b908f900b6132c3565b613f58565b6152f4565b82546152f4906152c990600160801b9004600f90810b810b908f900b6132a7565b8354600f9190910b6001600160801b03908116600160801b0291161790925550909c9b505050505050505050505050565b8060020b8260020b8161533457fe5b0760020b1561534257600080fd5b60008061535d8360020b8560020b8161535757fe5b056144b6565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b126153d1575050600182015460028301546153e4565b8360010154880391508360020154870390505b6000808b60020b8b60020b121561540657505060018301546002840154615419565b84600101548a0391508460020154890390505b92909803979097039b96909503949094039850939650505050505050565b6040805160a08101825285546001600160801b0390811682526001870154602083015260028701549282019290925260038601548083166060830152600160801b900490911660808201526000600f85900b6154d65781516001600160801b03166154ce576040805162461bcd60e51b815260206004820152600260248201526104e560f41b604482015290519081900360640190fd5b5080516154e5565b81516154e290866135ef565b90505b60006155098360200151860384600001516001600160801b0316600160801b6132d9565b9050600061552f8460400151860385600001516001600160801b0316600160801b6132d9565b905086600f0b6000146155565787546001600160801b0319166001600160801b0384161788555b60018801869055600288018590556001600160801b03821615158061558457506000816001600160801b0316115b156155c2576003880180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b5050505050505050565b600290810b810b6000908152602092909252604082208281556001810183905590810182905560030155565b806001600160a01b0381168114612beb57600080fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160808101825260008082526020820181905291810182905260608101919091529056fea164736f6c6343000706000a
|
608060405234801561001057600080fd5b50600436106101ae5760003560e01c806370cf754a116100ee578063c45a015511610097578063ddca3f4311610071578063ddca3f4314610800578063f305839914610820578063f30dba9314610828578063f637731d146108aa576101ae565b8063c45a0155146107d1578063d0c93a7c146107d9578063d21220a7146107f8576101ae565b8063883bdbfd116100c8578063883bdbfd14610633578063a34123a71461073c578063a38807f214610776576101ae565b806370cf754a146105c65780638206a4d1146105ce57806385b66729146105f6576101ae565b80633850c7bd1161015b578063490e6cbc11610135578063490e6cbc146104705780634f1eb3d8146104fc578063514ea4bf1461054d5780635339c296146105a6576101ae565b80633850c7bd1461035b5780633c8a7d8d146103b45780634614131914610456576101ae565b80631ad8b03b1161018c5780631ad8b03b146102aa578063252c09d7146102e157806332148f6714610338576101ae565b80630dfe1681146101b3578063128acb08146101d75780631a68650214610286575b600080fd5b6101bb6108d0565b604080516001600160a01b039092168252519081900360200190f35b61026d600480360360a08110156101ed57600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a08101608082013564010000000081111561022e57600080fd5b82018360208201111561024057600080fd5b8035906020019184600183028401116401000000008311171561026257600080fd5b5090925090506108f4565b6040805192835260208301919091528051918290030190f35b61028e6114ad565b604080516001600160801b039092168252519081900360200190f35b6102b26114bc565b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102fe600480360360208110156102f757600080fd5b50356114d6565b6040805163ffffffff909516855260069390930b60208501526001600160a01b039091168383015215156060830152519081900360800190f35b6103596004803603602081101561034e57600080fd5b503561ffff1661151c565b005b610363611616565b604080516001600160a01b03909816885260029690960b602088015261ffff9485168787015292841660608701529216608085015260ff90911660a0840152151560c0830152519081900360e00190f35b61026d600480360360a08110156103ca57600080fd5b6001600160a01b03823516916020810135600290810b92604083013590910b916001600160801b036060820135169181019060a08101608082013564010000000081111561041757600080fd5b82018360208201111561042957600080fd5b8035906020019184600183028401116401000000008311171561044b57600080fd5b509092509050611666565b61045e611922565b60408051918252519081900360200190f35b6103596004803603608081101561048657600080fd5b6001600160a01b0382351691602081013591604082013591908101906080810160608201356401000000008111156104bd57600080fd5b8201836020820111156104cf57600080fd5b803590602001918460018302840111640100000000831117156104f157600080fd5b509092509050611928565b6102b2600480360360a081101561051257600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b0360608201358116916080013516611d83565b61056a6004803603602081101561056357600080fd5b5035611f9d565b604080516001600160801b0396871681526020810195909552848101939093529084166060840152909216608082015290519081900360a00190f35b61045e600480360360208110156105bc57600080fd5b503560010b611fda565b61028e611fec565b610359600480360360408110156105e457600080fd5b5060ff81358116916020013516612010565b6102b26004803603606081101561060c57600080fd5b506001600160a01b03813516906001600160801b036020820135811691604001351661220f565b6106a36004803603602081101561064957600080fd5b81019060208101813564010000000081111561066457600080fd5b82018360208201111561067657600080fd5b8035906020019184602083028401116401000000008311171561069857600080fd5b5090925090506124dc565b604051808060200180602001838103835285818151815260200191508051906020019060200280838360005b838110156106e75781810151838201526020016106cf565b50505050905001838103825284818151815260200191508051906020019060200280838360005b8381101561072657818101518382015260200161070e565b5050505090500194505050505060405180910390f35b61026d6004803603606081101561075257600080fd5b508035600290810b91602081013590910b90604001356001600160801b0316612569565b6107a06004803603604081101561078c57600080fd5b508035600290810b9160200135900b6126e0565b6040805160069490940b84526001600160a01b03909216602084015263ffffffff1682820152519081900360600190f35b6101bb6128d7565b6107e16128fb565b6040805160029290920b8252519081900360200190f35b6101bb61291f565b610808612943565b6040805162ffffff9092168252519081900360200190f35b61045e612967565b6108486004803603602081101561083e57600080fd5b503560020b61296d565b604080516001600160801b039099168952600f9790970b602089015287870195909552606087019390935260069190910b60808601526001600160a01b031660a085015263ffffffff1660c0840152151560e083015251908190036101000190f35b610359600480360360208110156108c057600080fd5b50356001600160a01b03166129db565b7f000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec781565b6000806108ff612bf0565b85610936576040805162461bcd60e51b8152602060048201526002602482015261415360f01b604482015290519081900360640190fd5b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526109ef576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b87610a3a5780600001516001600160a01b0316866001600160a01b0316118015610a35575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038716105b610a6c565b80600001516001600160a01b0316866001600160a01b0316108015610a6c57506401000276a36001600160a01b038716115b610aa3576040805162461bcd60e51b815260206004820152600360248201526214d41360ea1b604482015290519081900360640190fd5b6000805460ff60f01b191681556040805160c08101909152808a610ad25760048460a0015160ff16901c610ae5565b60108460a0015160ff1681610ae357fe5b065b60ff1681526004546001600160801b03166020820152604001610b06612c27565b63ffffffff168152602001600060060b815260200160006001600160a01b031681526020016000151581525090506000808913905060006040518060e001604052808b81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018c610b8257600254610b86565b6001545b815260200160006001600160801b0316815260200184602001516001600160801b031681525090505b805115801590610bd55750886001600160a01b031681604001516001600160a01b031614155b15610f9f57610be261560e565b60408201516001600160a01b031681526060820151610c25906006907f000000000000000000000000000000000000000000000000000000000000003c8f612c2b565b15156040830152600290810b810b60208301819052620d89e719910b1215610c5657620d89e7196020820152610c75565b6020810151620d89e860029190910b1315610c7557620d89e860208201525b610c828160200151612d6d565b6001600160a01b031660608201526040820151610d13908d610cbc578b6001600160a01b031683606001516001600160a01b031611610cd6565b8b6001600160a01b031683606001516001600160a01b0316105b610ce4578260600151610ce6565b8b5b60c085015185517f0000000000000000000000000000000000000000000000000000000000000bb861309f565b60c085015260a084015260808301526001600160a01b031660408301528215610d7557610d498160c00151826080015101613291565b825103825260a0810151610d6b90610d6090613291565b6020840151906132a7565b6020830152610db0565b610d828160a00151613291565b825101825260c08101516080820151610daa91610d9f9101613291565b6020840151906132c3565b60208301525b835160ff1615610df6576000846000015160ff168260c0015181610dd057fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610e3557610e298160c00151600160801b8460c001516001600160801b03166132d9565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610f5e57806040015115610f35578360a00151610ebf57610e9d846040015160008760200151886040015188602001518a606001516008613389909695949392919063ffffffff16565b6001600160a01b03166080860152600690810b900b6060850152600160a08501525b6000610f0b82602001518e610ed657600154610edc565b84608001515b8f610eeb578560800151610eef565b6002545b608089015160608a015160408b0151600595949392919061351c565b90508c15610f17576000035b610f258360c00151826135ef565b6001600160801b031660c0840152505b8b610f44578060200151610f4d565b60018160200151035b600290810b900b6060830152610f99565b80600001516001600160a01b031682604001516001600160a01b031614610f9957610f8c82604001516136a5565b600290810b900b60608301525b50610baf565b836020015160020b816060015160020b1461107a57600080610fed86604001518660400151886020015188602001518a606001518b6080015160086139d1909695949392919063ffffffff16565b604085015160608601516000805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b93909316929092029190911773ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03909116179055506110ac9050565b60408101516000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039092169190911790555b8060c001516001600160801b031683602001516001600160801b0316146110f25760c0810151600480546001600160801b0319166001600160801b039092169190911790555b8a1561114257608081015160015560a08101516001600160801b03161561113d5760a0810151600380546001600160801b031981166001600160801b03918216909301169190911790555b611188565b608081015160025560a08101516001600160801b0316156111885760a0810151600380546001600160801b03808216600160801b92839004821690940116029190911790555b8115158b1515146111a157602081015181518b036111ae565b80600001518a0381602001515b90965094508a156112e75760008512156111f0576111f07f000000000000000000000000fc82bb4ba86045af6f327323a46e80412b91b27d8d87600003613b86565b60006111fa613cd4565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b15801561127e57600080fd5b505af1158015611292573d6000803e3d6000fd5b5050505061129e613cd4565b6112a88289613e0d565b11156112e1576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b50611411565b600086121561131e5761131e7f000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec78d88600003613b86565b6000611328613e1d565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506113cc613e1d565b6113d68288613e0d565b111561140f576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b505b60408082015160c083015160608085015184518b8152602081018b90526001600160a01b03948516818701526001600160801b039093169183019190915260020b60808201529151908e169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679181900360a00190a350506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b6004546001600160801b031681565b6003546001600160801b0380821691600160801b90041682565b60088161ffff81106114e757600080fd5b015463ffffffff81169150640100000000810460060b90600160581b81046001600160a01b031690600160f81b900460ff1684565b600054600160f01b900460ff16611560576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611575612bf0565b60008054600160d81b900461ffff169061159160088385613eb5565b6000805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115fe576040805161ffff80851682528316602082015281517fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a929181900390910190a15b50506000805460ff60f01b1916600160f01b17905550565b6000546001600160a01b03811690600160a01b810460020b9061ffff600160b81b8204811691600160c81b8104821691600160d81b8204169060ff600160e81b8204811691600160f01b90041687565b600080548190600160f01b900460ff166116ad576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b191690556001600160801b0385166116cd57600080fd5b60008061171b60405180608001604052808c6001600160a01b031681526020018b60020b81526020018a60020b81526020016117118a6001600160801b0316613f58565b600f0b9052613f69565b9250925050819350809250600080600086111561173d5761173a613cd4565b91505b841561174e5761174b613e1d565b90505b336001600160a01b031663d348799787878b8b6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156117d057600080fd5b505af11580156117e4573d6000803e3d6000fd5b50505050600086111561183b576117f9613cd4565b6118038388613e0d565b111561183b576040805162461bcd60e51b815260206004820152600260248201526104d360f41b604482015290519081900360640190fd5b841561188b57611849613e1d565b6118538287613e0d565b111561188b576040805162461bcd60e51b81526020600482015260026024820152614d3160f01b604482015290519081900360640190fd5b8960020b8b60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8b8b60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a450506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b60025481565b600054600160f01b900460ff1661196c576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611981612bf0565b6004546001600160801b0316806119c3576040805162461bcd60e51b81526020600482015260016024820152601360fa1b604482015290519081900360640190fd5b60006119f8867f0000000000000000000000000000000000000000000000000000000000000bb862ffffff16620f42406141a9565b90506000611a2f867f0000000000000000000000000000000000000000000000000000000000000bb862ffffff16620f42406141a9565b90506000611a3b613cd4565b90506000611a47613e1d565b90508815611a7a57611a7a7f000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec78b8b613b86565b8715611aab57611aab7f000000000000000000000000fc82bb4ba86045af6f327323a46e80412b91b27d8b8a613b86565b336001600160a01b031663e9cbafb085858a8a6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b158015611b2d57600080fd5b505af1158015611b41573d6000803e3d6000fd5b505050506000611b4f613cd4565b90506000611b5b613e1d565b905081611b688588613e0d565b1115611ba0576040805162461bcd60e51b8152602060048201526002602482015261046360f41b604482015290519081900360640190fd5b80611bab8487613e0d565b1115611be3576040805162461bcd60e51b8152602060048201526002602482015261463160f01b604482015290519081900360640190fd5b8382038382038115611c725760008054600160e81b9004600f16908115611c16578160ff168481611c1057fe5b04611c19565b60005b90506001600160801b03811615611c4c57600380546001600160801b038082168401166001600160801b03199091161790555b611c66818503600160801b8d6001600160801b03166132d9565b60018054909101905550505b8015611cfd5760008054600160e81b900460041c600f16908115611ca2578160ff168381611c9c57fe5b04611ca5565b60005b90506001600160801b03811615611cd757600380546001600160801b03600160801b8083048216850182160291161790555b611cf1818403600160801b8d6001600160801b03166132d9565b60028054909101905550505b8d6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338f8f86866040518085815260200184815260200183815260200182815260200194505050505060405180910390a350506000805460ff60f01b1916600160f01b179055505050505050505050505050565b600080548190600160f01b900460ff16611dca576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19168155611de460073389896141e3565b60038101549091506001600160801b0390811690861611611e055784611e14565b60038101546001600160801b03165b60038201549093506001600160801b03600160801b909104811690851611611e3c5783611e52565b6003810154600160801b90046001600160801b03165b91506001600160801b03831615611eb7576003810180546001600160801b031981166001600160801b03918216869003821617909155611eb7907f000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7908a908616613b86565b6001600160801b03821615611f1d576003810180546001600160801b03600160801b808304821686900382160291811691909117909155611f1d907f000000000000000000000000fc82bb4ba86045af6f327323a46e80412b91b27d908a908516613b86565b604080516001600160a01b038a1681526001600160801b0380861660208301528416818301529051600288810b92908a900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a4506000805460ff60f01b1916600160f01b17905590969095509350505050565b60076020526000908152604090208054600182015460028301546003909301546001600160801b0392831693919281811691600160801b90041685565b60066020526000908152604090205481565b7f0000000000000000000000000000000000023746e6a58dcb13d4af821b93f06281565b600054600160f01b900460ff16612054576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9841691638da5cb5b916004808301926020929190829003018186803b1580156120c157600080fd5b505afa1580156120d5573d6000803e3d6000fd5b505050506040513d60208110156120eb57600080fd5b50516001600160a01b0316331461210157600080fd5b60ff82161580612124575060048260ff16101580156121245750600a8260ff1611155b801561214e575060ff8116158061214e575060048160ff161015801561214e5750600a8160ff1611155b61215757600080fd5b60008054610ff0600484901b16840160ff908116600160e81b9081027fffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff841617909355919004167f973d8d92bb299f4af6ce49b52a8adb85ae46b9f214c4c4fc06ac77401237b1336010826040805160ff9390920683168252600f600486901c16602083015286831682820152918516606082015290519081900360800190a150506000805460ff60f01b1916600160f01b17905550565b600080548190600160f01b900460ff16612256576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9841691638da5cb5b916004808301926020929190829003018186803b1580156122c357600080fd5b505afa1580156122d7573d6000803e3d6000fd5b505050506040513d60208110156122ed57600080fd5b50516001600160a01b0316331461230357600080fd5b6003546001600160801b039081169085161161231f578361232c565b6003546001600160801b03165b6003549092506001600160801b03600160801b9091048116908416116123525782612366565b600354600160801b90046001600160801b03165b90506001600160801b038216156123e7576003546001600160801b038381169116141561239557600019909101905b600380546001600160801b031981166001600160801b039182168590038216179091556123e7907f000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec79087908516613b86565b6001600160801b0381161561246d576003546001600160801b03828116600160801b90920416141561241857600019015b600380546001600160801b03600160801b80830482168590038216029181169190911790915561246d907f000000000000000000000000fc82bb4ba86045af6f327323a46e80412b91b27d9087908416613b86565b604080516001600160801b0380851682528316602082015281516001600160a01b0388169233927f596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151929081900390910190a36000805460ff60f01b1916600160f01b1790559094909350915050565b6060806124e7612bf0565b61255e6124f2612c27565b858580806020026020016040519081016040528093929190818152602001838360200280828437600092018290525054600454600896959450600160a01b820460020b935061ffff600160b81b8304811693506001600160801b0390911691600160c81b900416614247565b915091509250929050565b600080548190600160f01b900460ff166125b0576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916815560408051608081018252338152600288810b602083015287900b918101919091528190819061260990606081016125fc6001600160801b038a16613f58565b600003600f0b9052613f69565b925092509250816000039450806000039350600085118061262a5750600084115b15612669576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b604080516001600160801b0388168152602081018790528082018690529051600289810b92908b900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a450506000805460ff60f01b1916600160f01b179055509094909350915050565b60008060006126ed612bf0565b6126f785856143a1565b600285810b810b60009081526005602052604080822087840b90930b825281206003830154600681900b9367010000000000000082046001600160a01b0316928492600160d81b810463ffffffff169284929091600160f81b900460ff168061275f57600080fd5b6003820154600681900b985067010000000000000081046001600160a01b03169650600160d81b810463ffffffff169450600160f81b900460ff16806127a457600080fd5b50506040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b810b6020840181905261ffff600160b81b8404811695850195909552600160c81b830485166060850152600160d81b8304909416608084015260ff600160e81b8304811660a0850152600160f01b909204909116151560c08301529093508e810b91900b1215905061284d575093909403965090039350900390506128d0565b8a60020b816020015160020b12156128c1576000612869612c27565b602083015160408401516004546060860151939450600093849361289f936008938893879392916001600160801b031690613389565b9a9003989098039b5050949096039290920396509091030392506128d0915050565b50949093039650039350900390505b9250925092565b7f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98481565b7f000000000000000000000000000000000000000000000000000000000000003c81565b7f000000000000000000000000fc82bb4ba86045af6f327323a46e80412b91b27d81565b7f0000000000000000000000000000000000000000000000000000000000000bb881565b60015481565b60056020526000908152604090208054600182015460028301546003909301546001600160801b03831693600160801b909304600f0b9290600681900b9067010000000000000081046001600160a01b031690600160d81b810463ffffffff1690600160f81b900460ff1688565b6000546001600160a01b031615612a1e576040805162461bcd60e51b8152602060048201526002602482015261414960f01b604482015290519081900360640190fd5b6000612a29826136a5565b9050600080612a41612a39612c27565b60089061446a565b6040805160e0810182526001600160a01b038816808252600288810b6020808501829052600085870181905261ffff898116606088018190529089166080880181905260a08801839052600160c0909801979097528154600160f01b73ffffffffffffffffffffffffffffffffffffffff19909116871762ffffff60a01b1916600160a01b62ffffff9787900b9790971696909602959095177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9091021761ffff60d81b1916600160d81b909602959095177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1692909217909355835191825281019190915281519395509193507f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9592918290030190a150505050565b60008082600281900b620d89e71981612b9957fe5b05029050600083600281900b620d89e881612bb057fe5b0502905060008460020b83830360020b81612bc757fe5b0560010190508062ffffff166001600160801b03801681612be457fe5b0493505050505b919050565b306001600160a01b037f0000000000000000000000003902428a74a08a91e2cb2fd834de75e69974fe671614612c2557600080fd5b565b4290565b60008060008460020b8660020b81612c3f57fe5b05905060008660020b128015612c6657508460020b8660020b81612c5f57fe5b0760020b15155b15612c7057600019015b8315612ce557600080612c82836144b6565b600182810b810b600090815260208d9052604090205460ff83169190911b80016000190190811680151597509294509092509085612cc757888360ff16860302612cda565b88612cd1826144c8565b840360ff168603025b965050505050612d63565b600080612cf4836001016144b6565b91509150600060018260ff166001901b031990506000818b60008660010b60010b8152602001908152602001600020541690508060001415955085612d4657888360ff0360ff16866001010102612d5c565b8883612d5183614568565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b12612d84578260020b612d8c565b8260020b6000035b9050620d89e8811115612dca576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612dde57600160801b612df0565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e24576ffff97272373d413259a46990580e213a0260801c5b6004821615612e43576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e62576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e81576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612ea0576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612ebf576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ede576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612efe576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f1e576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f3e576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f5e576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f7e576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f9e576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612fbe576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fde576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612fff576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561301f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561303e576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561305b576b048a170391f7dc42444e8fa20260801c5b60008460020b131561307657806000198161307257fe5b0490505b64010000000081061561308a57600161308d565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906131245760006130d88989620f42400362ffffff16620f42406132d9565b9050826130f1576130ec8c8c8c6001614652565b6130fe565b6130fe8b8d8c60016146cd565b955085811061310f578a965061311e565b61311b8c8b838661478a565b96505b5061316e565b8161313b576131368b8b8b60006146cd565b613148565b6131488a8c8b6000614652565b935083886000031061315c5789955061316e565b61316b8b8a8a600003856147d6565b95505b6001600160a01b038a81169087161482156131d15780801561318d5750815b6131a35761319e878d8c60016146cd565b6131a5565b855b95508080156131b2575081155b6131c8576131c3878d8c6000614652565b6131ca565b845b945061321b565b8080156131db5750815b6131f1576131ec8c888c6001614652565b6131f3565b855b9550808015613200575081155b613216576132118c888c60006146cd565b613218565b845b94505b8115801561322b57508860000385115b15613237578860000394505b81801561325657508a6001600160a01b0316876001600160a01b031614155b15613265578589039350613282565b61327f868962ffffff168a620f42400362ffffff166141a9565b93505b50505095509550955095915050565b6000600160ff1b82106132a357600080fd5b5090565b808203828113156000831215146132bd57600080fd5b92915050565b818101828112156000831215146132bd57600080fd5b600080806000198587098686029250828110908390030390508061330f576000841161330457600080fd5b508290049050613382565b80841161331b57600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008063ffffffff8716613430576000898661ffff1661ffff81106133aa57fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a161461341c57613419818a8988614822565b90505b806020015181604001519250925050613510565b8688036000806134458c8c858c8c8c8c6148d2565b91509150816000015163ffffffff168363ffffffff161415613477578160200151826040015194509450505050613510565b805163ffffffff8481169116141561349f578060200151816040015194509450505050613510565b8151815160208085015190840151918390039286039163ffffffff80841692908516910360060b816134cd57fe5b05028460200151018263ffffffff168263ffffffff1686604001518660400151036001600160a01b031602816134ff57fe5b048560400151019650965050505050505b97509795505050505050565b600295860b860b60009081526020979097526040909620600181018054909503909455938301805490920390915560038201805463ffffffff600160d81b6001600160a01b036701000000000000008085048216909603169094027fffffffffff0000000000000000000000000000000000000000ffffffffffffff90921691909117600681810b90960390950b66ffffffffffffff1666ffffffffffffff199095169490941782810485169095039093160263ffffffff60d81b1990931692909217905554600160801b9004600f0b90565b60008082600f0b121561365457826001600160801b03168260000384039150816001600160801b03161061364f576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b6132bd565b826001600160801b03168284019150816001600160801b031610156132bd576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b038316108015906136e1575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613716576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106137b757607f810383901c91506137c1565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146139c257886001600160a01b03166139a682612d6d565b6001600160a01b031611156139bb57816139bd565b805b6139c4565b815b9998505050505050505050565b6000806000898961ffff1661ffff81106139e757fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff161515606083015290925089161415613a575788859250925050613510565b8461ffff168461ffff16118015613a7857506001850361ffff168961ffff16145b15613a8557839150613a89565b8491505b8161ffff168960010161ffff1681613a9d57fe5b069250613aac81898989614822565b8a8461ffff1661ffff8110613abd57fe5b825191018054602084015160408501516060909501511515600160f81b027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b03909616600160581b027fff0000000000000000000000000000000000000000ffffffffffffffffffffff60069390930b66ffffffffffffff16640100000000026affffffffffffff000000001963ffffffff90971663ffffffff199095169490941795909516929092171692909217929092161790555097509795505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c025780518252601f199092019160209182019101613be3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c64576040519150601f19603f3d011682016040523d82523d6000602084013e613c69565b606091505b5091509150818015613c97575080511580613c975750808060200190516020811015613c9457600080fd5b50515b613ccd576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b5050505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec71693919290918291908083835b60208310613d6d5780518252601f199092019160209182019101613d4e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613dcd576040519150601f19603f3d011682016040523d82523d6000602084013e613dd2565b606091505b5091509150818015613de657506020815110155b613def57600080fd5b808060200190516020811015613e0457600080fd5b50519250505090565b808201828110156132bd57600080fd5b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000fc82bb4ba86045af6f327323a46e80412b91b27d16939192909182919080838360208310613d6d5780518252601f199092019160209182019101613d4e565b6000808361ffff1611613ef3576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b8261ffff168261ffff1611613f09575081613382565b825b8261ffff168161ffff161015613f4f576001858261ffff1661ffff8110613f2e57fe5b01805463ffffffff191663ffffffff92909216919091179055600101613f0b565b50909392505050565b80600f81900b8114612beb57600080fd5b6000806000613f76612bf0565b613f88846020015185604001516143a1565b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602080840182905261ffff600160b81b8404811685870152600160c81b84048116606080870191909152600160d81b8504909116608086015260ff600160e81b8504811660a0870152600160f01b909404909316151560c08501528851908901519489015192890151939461402c9491939092909190614acf565b93508460600151600f0b6000146141a157846020015160020b816020015160020b12156140815761407a6140638660200151612d6d565b6140708760400151612d6d565b8760600151614c84565b92506141a1565b846040015160020b816020015160020b12156141775760045460408201516001600160801b03909116906140d3906140b7612c27565b60208501516060860151608087015160089493929187916139d1565b6000805461ffff60c81b1916600160c81b61ffff938416021761ffff60b81b1916600160b81b939092169290920217905581516040870151614123919061411990612d6d565b8860600151614c84565b93506141416141358760200151612d6d565b83516060890151614cc8565b92506141518187606001516135ef565b600480546001600160801b0319166001600160801b0392909216919091179055506141a1565b61419e6141878660200151612d6d565b6141948760400151612d6d565b8760600151614cc8565b91505b509193909250565b60006141b68484846132d9565b9050600082806141c257fe5b84860911156133825760001981106141d957600080fd5b6001019392505050565b6040805160609490941b6bffffffffffffffffffffffff1916602080860191909152600293840b60e890811b60348701529290930b90911b60378401528051808403601a018152603a90930181528251928201929092206000908152929052902090565b60608060008361ffff1611614287576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b865167ffffffffffffffff8111801561429f57600080fd5b506040519080825280602002602001820160405280156142c9578160200160208202803683370190505b509150865167ffffffffffffffff811180156142e457600080fd5b5060405190808252806020026020018201604052801561430e578160200160208202803683370190505b50905060005b87518110156143945761433f8a8a8a848151811061432e57fe5b60200260200101518a8a8a8a613389565b84838151811061434b57fe5b6020026020010184848151811061435e57fe5b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b81525050508080600101915050614314565b5097509795505050505050565b8060020b8260020b126143e1576040805162461bcd60e51b8152602060048201526003602482015262544c5560e81b604482015290519081900360640190fd5b620d89e719600283900b1215614424576040805162461bcd60e51b8152602060048201526003602482015262544c4d60e81b604482015290519081900360640190fd5b620d89e8600282900b1315614466576040805162461bcd60e51b815260206004820152600360248201526254554d60e81b604482015290519081900360640190fd5b5050565b6040805160808101825263ffffffff9283168082526000602083018190529282019290925260016060909101819052835463ffffffff1916909117909116600160f81b17909155908190565b60020b600881901d9161010090910790565b60008082116144d657600080fd5b600160801b82106144e957608091821c91015b68010000000000000000821061450157604091821c91015b640100000000821061451557602091821c91015b62010000821061452757601091821c91015b610100821061453857600891821c91015b6010821061454857600491821c91015b6004821061455857600291821c91015b60028210612beb57600101919050565b600080821161457657600080fd5b5060ff6001600160801b0382161561459157607f1901614599565b608082901c91505b67ffffffffffffffff8216156145b257603f19016145ba565b604082901c91505b63ffffffff8216156145cf57601f19016145d7565b602082901c91505b61ffff8216156145ea57600f19016145f2565b601082901c91505b60ff821615614604576007190161460c565b600882901c91505b600f82161561461e5760031901614626565b600482901c91505b60038216156146385760011901614640565b600282901c91505b6001821615612beb5760001901919050565b6000836001600160a01b0316856001600160a01b03161115614672579293925b8161469f5761469a836001600160801b03168686036001600160a01b0316600160601b6132d9565b6146c2565b6146c2836001600160801b03168686036001600160a01b0316600160601b6141a9565b90505b949350505050565b6000836001600160a01b0316856001600160a01b031611156146ed579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661472957600080fd5b8361475957866001600160a01b031661474c8383896001600160a01b03166132d9565b8161475357fe5b0461477f565b61477f6147708383896001600160a01b03166141a9565b886001600160a01b0316614cf7565b979650505050505050565b600080856001600160a01b0316116147a157600080fd5b6000846001600160801b0316116147b757600080fd5b816147c95761469a8585856001614d02565b6146c28585856001614de3565b600080856001600160a01b0316116147ed57600080fd5b6000846001600160801b03161161480357600080fd5b816148155761469a8585856000614de3565b6146c28585856000614d02565b61482a61564a565b600085600001518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020016000856001600160801b03161161487e576001614880565b845b6001600160801b031673ffffffff00000000000000000000000000000000608085901b16816148ab57fe5b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b6148da61564a565b6148e261564a565b888561ffff1661ffff81106148f357fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff1615156060820152925061495890899089614ed8565b15614990578663ffffffff16826000015163ffffffff16141561497a57613510565b8161498783898988614822565b91509150613510565b888361ffff168660010161ffff16816149a557fe5b0661ffff1661ffff81106149b557fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909250614a6c57604080516080810182528a5463ffffffff811682526401000000008104600690810b810b900b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b614a7b88836000015189614ed8565b614ab2576040805162461bcd60e51b815260206004820152600360248201526213d31160ea1b604482015290519081900360640190fd5b614abf8989898887614f9b565b9150915097509795505050505050565b6000614ade60078787876141e3565b60015460025491925090600080600f87900b15614c24576000614aff612c27565b6000805460045492935090918291614b499160089186918591600160a01b810460020b9161ffff600160b81b83048116926001600160801b0390921691600160c81b900416613389565b9092509050614b8360058d8b8d8b8b87898b60007f0000000000000000000000000000000000023746e6a58dcb13d4af821b93f06261513b565b9450614bba60058c8b8d8b8b87898b60017f0000000000000000000000000000000000023746e6a58dcb13d4af821b93f06261513b565b93508415614bee57614bee60068d7f000000000000000000000000000000000000000000000000000000000000003c615325565b8315614c2057614c2060068c7f000000000000000000000000000000000000000000000000000000000000003c615325565b5050505b600080614c3660058c8c8b8a8a61538b565b9092509050614c47878a8484615437565b600089600f0b1215614c75578315614c6457614c6460058c6155cc565b8215614c7557614c7560058b6155cc565b50505050505095945050505050565b60008082600f0b12614caa57614ca5614ca085858560016146cd565b613291565b6146c5565b614cbd614ca085858560000360006146cd565b600003949350505050565b60008082600f0b12614ce457614ca5614ca08585856001614652565b614cbd614ca08585856000036000614652565b808204910615150190565b60008115614d755760006001600160a01b03841115614d3857614d3384600160601b876001600160801b03166132d9565b614d50565b6001600160801b038516606085901b81614d4e57fe5b045b9050614d6d614d686001600160a01b03881683613e0d565b6155f8565b9150506146c5565b60006001600160a01b03841115614da357614d9e84600160601b876001600160801b03166141a9565b614dba565b614dba606085901b6001600160801b038716614cf7565b905080866001600160a01b031611614dd157600080fd5b6001600160a01b0386160390506146c5565b600082614df15750836146c5565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b168215614e91576001600160a01b03861684810290858281614e3157fe5b041415614e6257818101828110614e6057614e5683896001600160a01b0316836141a9565b93505050506146c5565b505b614e8882614e83878a6001600160a01b03168681614e7c57fe5b0490613e0d565b614cf7565b925050506146c5565b6001600160a01b03861684810290858281614ea857fe5b04148015614eb557508082115b614ebe57600080fd5b808203614e56614d68846001600160a01b038b16846141a9565b60008363ffffffff168363ffffffff1611158015614f0257508363ffffffff168263ffffffff1611155b15614f1e578163ffffffff168363ffffffff1611159050613382565b60008463ffffffff168463ffffffff1611614f46578363ffffffff1664010000000001614f4e565b8363ffffffff165b64ffffffffff16905060008563ffffffff168463ffffffff1611614f7f578363ffffffff1664010000000001614f87565b8363ffffffff165b64ffffffffff169091111595945050505050565b614fa361564a565b614fab61564a565b60008361ffff168560010161ffff1681614fc157fe5b0661ffff169050600060018561ffff16830103905060005b506002818301048961ffff87168281614fee57fe5b0661ffff8110614ffa57fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290955061506557806001019250614fd9565b898661ffff16826001018161507657fe5b0661ffff811061508257fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094506000906150ed908b908b614ed8565b905080801561510657506151068a8a8760000151614ed8565b15615111575061512e565b8061512157600182039250615128565b8160010193505b50614fd9565b5050509550959350505050565b60028a810b900b600090815260208c90526040812080546001600160801b031682615166828d6135ef565b9050846001600160801b0316816001600160801b031611156151b4576040805162461bcd60e51b81526020600482015260026024820152614c4f60f01b604482015290519081900360640190fd5b6001600160801b03828116159082161581141594501561528a578c60020b8e60020b1361525a57600183018b9055600283018a90556003830180547fffffffffff0000000000000000000000000000000000000000ffffffffffffff166701000000000000006001600160a01b038c16021766ffffffffffffff191666ffffffffffffff60068b900b161763ffffffff60d81b1916600160d81b63ffffffff8a16021790555b6003830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b038216178355856152d35782546152ce906152c990600160801b9004600f90810b810b908f900b6132c3565b613f58565b6152f4565b82546152f4906152c990600160801b9004600f90810b810b908f900b6132a7565b8354600f9190910b6001600160801b03908116600160801b0291161790925550909c9b505050505050505050505050565b8060020b8260020b8161533457fe5b0760020b1561534257600080fd5b60008061535d8360020b8560020b8161535757fe5b056144b6565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b126153d1575050600182015460028301546153e4565b8360010154880391508360020154870390505b6000808b60020b8b60020b121561540657505060018301546002840154615419565b84600101548a0391508460020154890390505b92909803979097039b96909503949094039850939650505050505050565b6040805160a08101825285546001600160801b0390811682526001870154602083015260028701549282019290925260038601548083166060830152600160801b900490911660808201526000600f85900b6154d65781516001600160801b03166154ce576040805162461bcd60e51b815260206004820152600260248201526104e560f41b604482015290519081900360640190fd5b5080516154e5565b81516154e290866135ef565b90505b60006155098360200151860384600001516001600160801b0316600160801b6132d9565b9050600061552f8460400151860385600001516001600160801b0316600160801b6132d9565b905086600f0b6000146155565787546001600160801b0319166001600160801b0384161788555b60018801869055600288018590556001600160801b03821615158061558457506000816001600160801b0316115b156155c2576003880180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b5050505050505050565b600290810b810b6000908152602092909252604082208281556001810183905590810182905560030155565b806001600160a01b0381168114612beb57600080fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160808101825260008082526020820181905291810182905260608101919091529056fea164736f6c6343000706000a
|
{{
"language": "Solidity",
"sources": {
"contracts/UniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.7.6;\n\nimport './interfaces/IUniswapV3Pool.sol';\n\nimport './NoDelegateCall.sol';\n\nimport './libraries/LowGasSafeMath.sol';\nimport './libraries/SafeCast.sol';\nimport './libraries/Tick.sol';\nimport './libraries/TickBitmap.sol';\nimport './libraries/Position.sol';\nimport './libraries/Oracle.sol';\n\nimport './libraries/FullMath.sol';\nimport './libraries/FixedPoint128.sol';\nimport './libraries/TransferHelper.sol';\nimport './libraries/TickMath.sol';\nimport './libraries/LiquidityMath.sol';\nimport './libraries/SqrtPriceMath.sol';\nimport './libraries/SwapMath.sol';\n\nimport './interfaces/IUniswapV3PoolDeployer.sol';\nimport './interfaces/IUniswapV3Factory.sol';\nimport './interfaces/IERC20Minimal.sol';\nimport './interfaces/callback/IUniswapV3MintCallback.sol';\nimport './interfaces/callback/IUniswapV3SwapCallback.sol';\nimport './interfaces/callback/IUniswapV3FlashCallback.sol';\n\ncontract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Tick for mapping(int24 => Tick.Info);\n using TickBitmap for mapping(int16 => uint256);\n using Position for mapping(bytes32 => Position.Info);\n using Position for Position.Info;\n using Oracle for Oracle.Observation[65535];\n\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override factory;\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override token0;\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override token1;\n /// @inheritdoc IUniswapV3PoolImmutables\n uint24 public immutable override fee;\n\n /// @inheritdoc IUniswapV3PoolImmutables\n int24 public immutable override tickSpacing;\n\n /// @inheritdoc IUniswapV3PoolImmutables\n uint128 public immutable override maxLiquidityPerTick;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n /// @inheritdoc IUniswapV3PoolState\n Slot0 public override slot0;\n\n /// @inheritdoc IUniswapV3PoolState\n uint256 public override feeGrowthGlobal0X128;\n /// @inheritdoc IUniswapV3PoolState\n uint256 public override feeGrowthGlobal1X128;\n\n // accumulated protocol fees in token0/token1 units\n struct ProtocolFees {\n uint128 token0;\n uint128 token1;\n }\n /// @inheritdoc IUniswapV3PoolState\n ProtocolFees public override protocolFees;\n\n /// @inheritdoc IUniswapV3PoolState\n uint128 public override liquidity;\n\n /// @inheritdoc IUniswapV3PoolState\n mapping(int24 => Tick.Info) public override ticks;\n /// @inheritdoc IUniswapV3PoolState\n mapping(int16 => uint256) public override tickBitmap;\n /// @inheritdoc IUniswapV3PoolState\n mapping(bytes32 => Position.Info) public override positions;\n /// @inheritdoc IUniswapV3PoolState\n Oracle.Observation[65535] public override observations;\n\n /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance\n /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because\n /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.\n modifier lock() {\n require(slot0.unlocked, 'LOK');\n slot0.unlocked = false;\n _;\n slot0.unlocked = true;\n }\n\n /// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner()\n modifier onlyFactoryOwner() {\n require(msg.sender == IUniswapV3Factory(factory).owner());\n _;\n }\n\n constructor() {\n int24 _tickSpacing;\n (factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters();\n tickSpacing = _tickSpacing;\n\n maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);\n }\n\n /// @dev Common checks for valid tick inputs.\n function checkTicks(int24 tickLower, int24 tickUpper) private pure {\n require(tickLower < tickUpper, 'TLU');\n require(tickLower >= TickMath.MIN_TICK, 'TLM');\n require(tickUpper <= TickMath.MAX_TICK, 'TUM');\n }\n\n /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.\n function _blockTimestamp() internal view virtual returns (uint32) {\n return uint32(block.timestamp); // truncation is desired\n }\n\n /// @dev Get the pool's balance of token0\n /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n /// check\n function balance0() private view returns (uint256) {\n (bool success, bytes memory data) =\n token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));\n require(success && data.length >= 32);\n return abi.decode(data, (uint256));\n }\n\n /// @dev Get the pool's balance of token1\n /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n /// check\n function balance1() private view returns (uint256) {\n (bool success, bytes memory data) =\n token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));\n require(success && data.length >= 32);\n return abi.decode(data, (uint256));\n }\n\n /// @inheritdoc IUniswapV3PoolDerivedState\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n override\n noDelegateCall\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n )\n {\n checkTicks(tickLower, tickUpper);\n\n int56 tickCumulativeLower;\n int56 tickCumulativeUpper;\n uint160 secondsPerLiquidityOutsideLowerX128;\n uint160 secondsPerLiquidityOutsideUpperX128;\n uint32 secondsOutsideLower;\n uint32 secondsOutsideUpper;\n\n {\n Tick.Info storage lower = ticks[tickLower];\n Tick.Info storage upper = ticks[tickUpper];\n bool initializedLower;\n (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (\n lower.tickCumulativeOutside,\n lower.secondsPerLiquidityOutsideX128,\n lower.secondsOutside,\n lower.initialized\n );\n require(initializedLower);\n\n bool initializedUpper;\n (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (\n upper.tickCumulativeOutside,\n upper.secondsPerLiquidityOutsideX128,\n upper.secondsOutside,\n upper.initialized\n );\n require(initializedUpper);\n }\n\n Slot0 memory _slot0 = slot0;\n\n if (_slot0.tick < tickLower) {\n return (\n tickCumulativeLower - tickCumulativeUpper,\n secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,\n secondsOutsideLower - secondsOutsideUpper\n );\n } else if (_slot0.tick < tickUpper) {\n uint32 time = _blockTimestamp();\n (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =\n observations.observeSingle(\n time,\n 0,\n _slot0.tick,\n _slot0.observationIndex,\n liquidity,\n _slot0.observationCardinality\n );\n return (\n tickCumulative - tickCumulativeLower - tickCumulativeUpper,\n secondsPerLiquidityCumulativeX128 -\n secondsPerLiquidityOutsideLowerX128 -\n secondsPerLiquidityOutsideUpperX128,\n time - secondsOutsideLower - secondsOutsideUpper\n );\n } else {\n return (\n tickCumulativeUpper - tickCumulativeLower,\n secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,\n secondsOutsideUpper - secondsOutsideLower\n );\n }\n }\n\n /// @inheritdoc IUniswapV3PoolDerivedState\n function observe(uint32[] calldata secondsAgos)\n external\n view\n override\n noDelegateCall\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n return\n observations.observe(\n _blockTimestamp(),\n secondsAgos,\n slot0.tick,\n slot0.observationIndex,\n liquidity,\n slot0.observationCardinality\n );\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext)\n external\n override\n lock\n noDelegateCall\n {\n uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event\n uint16 observationCardinalityNextNew =\n observations.grow(observationCardinalityNextOld, observationCardinalityNext);\n slot0.observationCardinalityNext = observationCardinalityNextNew;\n if (observationCardinalityNextOld != observationCardinalityNextNew)\n emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev not locked because it initializes unlocked\n function initialize(uint160 sqrtPriceX96) external override {\n require(slot0.sqrtPriceX96 == 0, 'AI');\n\n int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);\n\n (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());\n\n slot0 = Slot0({\n sqrtPriceX96: sqrtPriceX96,\n tick: tick,\n observationIndex: 0,\n observationCardinality: cardinality,\n observationCardinalityNext: cardinalityNext,\n feeProtocol: 0,\n unlocked: true\n });\n\n emit Initialize(sqrtPriceX96, tick);\n }\n\n struct ModifyPositionParams {\n // the address that owns the position\n address owner;\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // any change in liquidity\n int128 liquidityDelta;\n }\n\n /// @dev Effect some changes to a position\n /// @param params the position details and the change to the position's liquidity to effect\n /// @return position a storage pointer referencing the position with the given owner and tick range\n /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient\n /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient\n function _modifyPosition(ModifyPositionParams memory params)\n private\n noDelegateCall\n returns (\n Position.Info storage position,\n int256 amount0,\n int256 amount1\n )\n {\n checkTicks(params.tickLower, params.tickUpper);\n\n Slot0 memory _slot0 = slot0; // SLOAD for gas optimization\n\n position = _updatePosition(\n params.owner,\n params.tickLower,\n params.tickUpper,\n params.liquidityDelta,\n _slot0.tick\n );\n\n if (params.liquidityDelta != 0) {\n if (_slot0.tick < params.tickLower) {\n // current tick is below the passed range; liquidity can only become in range by crossing from left to\n // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it\n amount0 = SqrtPriceMath.getAmount0Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n } else if (_slot0.tick < params.tickUpper) {\n // current tick is inside the passed range\n uint128 liquidityBefore = liquidity; // SLOAD for gas optimization\n\n // write an oracle entry\n (slot0.observationIndex, slot0.observationCardinality) = observations.write(\n _slot0.observationIndex,\n _blockTimestamp(),\n _slot0.tick,\n liquidityBefore,\n _slot0.observationCardinality,\n _slot0.observationCardinalityNext\n );\n\n amount0 = SqrtPriceMath.getAmount0Delta(\n _slot0.sqrtPriceX96,\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n amount1 = SqrtPriceMath.getAmount1Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n _slot0.sqrtPriceX96,\n params.liquidityDelta\n );\n\n liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);\n } else {\n // current tick is above the passed range; liquidity can only become in range by crossing from right to\n // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it\n amount1 = SqrtPriceMath.getAmount1Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n }\n }\n }\n\n /// @dev Gets and updates a position with the given liquidity delta\n /// @param owner the owner of the position\n /// @param tickLower the lower tick of the position's tick range\n /// @param tickUpper the upper tick of the position's tick range\n /// @param tick the current tick, passed to avoid sloads\n function _updatePosition(\n address owner,\n int24 tickLower,\n int24 tickUpper,\n int128 liquidityDelta,\n int24 tick\n ) private returns (Position.Info storage position) {\n position = positions.get(owner, tickLower, tickUpper);\n\n uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization\n uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization\n\n // if we need to update the ticks, do it\n bool flippedLower;\n bool flippedUpper;\n if (liquidityDelta != 0) {\n uint32 time = _blockTimestamp();\n (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =\n observations.observeSingle(\n time,\n 0,\n slot0.tick,\n slot0.observationIndex,\n liquidity,\n slot0.observationCardinality\n );\n\n flippedLower = ticks.update(\n tickLower,\n tick,\n liquidityDelta,\n _feeGrowthGlobal0X128,\n _feeGrowthGlobal1X128,\n secondsPerLiquidityCumulativeX128,\n tickCumulative,\n time,\n false,\n maxLiquidityPerTick\n );\n flippedUpper = ticks.update(\n tickUpper,\n tick,\n liquidityDelta,\n _feeGrowthGlobal0X128,\n _feeGrowthGlobal1X128,\n secondsPerLiquidityCumulativeX128,\n tickCumulative,\n time,\n true,\n maxLiquidityPerTick\n );\n\n if (flippedLower) {\n tickBitmap.flipTick(tickLower, tickSpacing);\n }\n if (flippedUpper) {\n tickBitmap.flipTick(tickUpper, tickSpacing);\n }\n }\n\n (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =\n ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128);\n\n position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);\n\n // clear any tick data that is no longer needed\n if (liquidityDelta < 0) {\n if (flippedLower) {\n ticks.clear(tickLower);\n }\n if (flippedUpper) {\n ticks.clear(tickUpper);\n }\n }\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev noDelegateCall is applied indirectly via _modifyPosition\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external override lock returns (uint256 amount0, uint256 amount1) {\n require(amount > 0);\n (, int256 amount0Int, int256 amount1Int) =\n _modifyPosition(\n ModifyPositionParams({\n owner: recipient,\n tickLower: tickLower,\n tickUpper: tickUpper,\n liquidityDelta: int256(amount).toInt128()\n })\n );\n\n amount0 = uint256(amount0Int);\n amount1 = uint256(amount1Int);\n\n uint256 balance0Before;\n uint256 balance1Before;\n if (amount0 > 0) balance0Before = balance0();\n if (amount1 > 0) balance1Before = balance1();\n IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);\n if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');\n if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');\n\n emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external override lock returns (uint128 amount0, uint128 amount1) {\n // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}\n Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);\n\n amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;\n amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;\n\n if (amount0 > 0) {\n position.tokensOwed0 -= amount0;\n TransferHelper.safeTransfer(token0, recipient, amount0);\n }\n if (amount1 > 0) {\n position.tokensOwed1 -= amount1;\n TransferHelper.safeTransfer(token1, recipient, amount1);\n }\n\n emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev noDelegateCall is applied indirectly via _modifyPosition\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external override lock returns (uint256 amount0, uint256 amount1) {\n (Position.Info storage position, int256 amount0Int, int256 amount1Int) =\n _modifyPosition(\n ModifyPositionParams({\n owner: msg.sender,\n tickLower: tickLower,\n tickUpper: tickUpper,\n liquidityDelta: -int256(amount).toInt128()\n })\n );\n\n amount0 = uint256(-amount0Int);\n amount1 = uint256(-amount1Int);\n\n if (amount0 > 0 || amount1 > 0) {\n (position.tokensOwed0, position.tokensOwed1) = (\n position.tokensOwed0 + uint128(amount0),\n position.tokensOwed1 + uint128(amount1)\n );\n }\n\n emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external override noDelegateCall returns (int256 amount0, int256 amount1) {\n require(amountSpecified != 0, 'AS');\n\n Slot0 memory slot0Start = slot0;\n\n require(slot0Start.unlocked, 'LOK');\n require(\n zeroForOne\n ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO\n : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,\n 'SPL'\n );\n\n slot0.unlocked = false;\n\n SwapCache memory cache =\n SwapCache({\n liquidityStart: liquidity,\n blockTimestamp: _blockTimestamp(),\n feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4),\n secondsPerLiquidityCumulativeX128: 0,\n tickCumulative: 0,\n computedLatestObservation: false\n });\n\n bool exactInput = amountSpecified > 0;\n\n SwapState memory state =\n SwapState({\n amountSpecifiedRemaining: amountSpecified,\n amountCalculated: 0,\n sqrtPriceX96: slot0Start.sqrtPriceX96,\n tick: slot0Start.tick,\n feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,\n protocolFee: 0,\n liquidity: cache.liquidityStart\n });\n\n // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(\n state.tick,\n tickSpacing,\n zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)\n ? sqrtPriceLimitX96\n : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n fee\n );\n\n if (exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee\n if (cache.feeProtocol > 0) {\n uint256 delta = step.feeAmount / cache.feeProtocol;\n step.feeAmount -= delta;\n state.protocolFee += uint128(delta);\n }\n\n // update global fee tracker\n if (state.liquidity > 0)\n state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n // check for the placeholder value, which we replace with the actual value the first time the swap\n // crosses an initialized tick\n if (!cache.computedLatestObservation) {\n (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(\n cache.blockTimestamp,\n 0,\n slot0Start.tick,\n slot0Start.observationIndex,\n cache.liquidityStart,\n slot0Start.observationCardinality\n );\n cache.computedLatestObservation = true;\n }\n int128 liquidityNet =\n ticks.cross(\n step.tickNext,\n (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),\n (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),\n cache.secondsPerLiquidityCumulativeX128,\n cache.tickCumulative,\n cache.blockTimestamp\n );\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n }\n\n state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n // update tick and write an oracle entry if the tick change\n if (state.tick != slot0Start.tick) {\n (uint16 observationIndex, uint16 observationCardinality) =\n observations.write(\n slot0Start.observationIndex,\n cache.blockTimestamp,\n slot0Start.tick,\n cache.liquidityStart,\n slot0Start.observationCardinality,\n slot0Start.observationCardinalityNext\n );\n (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (\n state.sqrtPriceX96,\n state.tick,\n observationIndex,\n observationCardinality\n );\n } else {\n // otherwise just update the price\n slot0.sqrtPriceX96 = state.sqrtPriceX96;\n }\n\n // update liquidity if it changed\n if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;\n\n // update fee growth global and, if necessary, protocol fees\n // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees\n if (zeroForOne) {\n feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;\n if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;\n } else {\n feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;\n if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;\n }\n\n (amount0, amount1) = zeroForOne == exactInput\n ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);\n\n // do the transfers and collect payment\n if (zeroForOne) {\n if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));\n\n uint256 balance0Before = balance0();\n IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);\n require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');\n } else {\n if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));\n\n uint256 balance1Before = balance1();\n IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);\n require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');\n }\n\n emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick);\n slot0.unlocked = true;\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external override lock noDelegateCall {\n uint128 _liquidity = liquidity;\n require(_liquidity > 0, 'L');\n\n uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);\n uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);\n uint256 balance0Before = balance0();\n uint256 balance1Before = balance1();\n\n if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);\n if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);\n\n IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);\n\n uint256 balance0After = balance0();\n uint256 balance1After = balance1();\n\n require(balance0Before.add(fee0) <= balance0After, 'F0');\n require(balance1Before.add(fee1) <= balance1After, 'F1');\n\n // sub is safe because we know balanceAfter is gt balanceBefore by at least fee\n uint256 paid0 = balance0After - balance0Before;\n uint256 paid1 = balance1After - balance1Before;\n\n if (paid0 > 0) {\n uint8 feeProtocol0 = slot0.feeProtocol % 16;\n uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0;\n if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);\n feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);\n }\n if (paid1 > 0) {\n uint8 feeProtocol1 = slot0.feeProtocol >> 4;\n uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1;\n if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);\n feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);\n }\n\n emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);\n }\n\n /// @inheritdoc IUniswapV3PoolOwnerActions\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {\n require(\n (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&\n (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))\n );\n uint8 feeProtocolOld = slot0.feeProtocol;\n slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);\n emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);\n }\n\n /// @inheritdoc IUniswapV3PoolOwnerActions\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) {\n amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;\n amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;\n\n if (amount0 > 0) {\n if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings\n protocolFees.token0 -= amount0;\n TransferHelper.safeTransfer(token0, recipient, amount0);\n }\n if (amount1 > 0) {\n if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings\n protocolFees.token1 -= amount1;\n TransferHelper.safeTransfer(token1, recipient, amount1);\n }\n\n emit CollectProtocol(msg.sender, recipient, amount0, amount1);\n }\n}\n"
},
"contracts/interfaces/IUniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n IUniswapV3PoolImmutables,\n IUniswapV3PoolState,\n IUniswapV3PoolDerivedState,\n IUniswapV3PoolActions,\n IUniswapV3PoolOwnerActions,\n IUniswapV3PoolEvents\n{\n\n}\n"
},
"contracts/NoDelegateCall.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.7.6;\n\n/// @title Prevents delegatecall to a contract\n/// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract\nabstract contract NoDelegateCall {\n /// @dev The original address of this contract\n address private immutable original;\n\n constructor() {\n // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.\n // In other words, this variable won't change when it's checked at runtime.\n original = address(this);\n }\n\n /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,\n /// and the use of immutable means the address bytes are copied in every place the modifier is used.\n function checkNotDelegateCall() private view {\n require(address(this) == original);\n }\n\n /// @notice Prevents delegatecall into the modified method\n modifier noDelegateCall() {\n checkNotDelegateCall();\n _;\n }\n}\n"
},
"contracts/libraries/LowGasSafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.0;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary LowGasSafeMath {\n /// @notice Returns x + y, reverts if sum overflows uint256\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x + y) >= x);\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x - y) <= x);\n }\n\n /// @notice Returns x * y, reverts if overflows\n /// @param x The multiplicand\n /// @param y The multiplier\n /// @return z The product of x and y\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require(x == 0 || (z = x * y) / x == y);\n }\n\n /// @notice Returns x + y, reverts if overflows or underflows\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x + y) >= x == (y >= 0));\n }\n\n /// @notice Returns x - y, reverts if overflows or underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x - y) <= x == (y >= 0));\n }\n}\n"
},
"contracts/libraries/SafeCast.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\n }\n}\n"
},
"contracts/libraries/Tick.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './TickMath.sol';\nimport './LiquidityMath.sol';\n\n/// @title Tick\n/// @notice Contains functions for managing tick processes and relevant calculations\nlibrary Tick {\n using LowGasSafeMath for int256;\n using SafeCast for int256;\n\n // info stored for each initialized individual tick\n struct Info {\n // the total position liquidity that references this tick\n uint128 liquidityGross;\n // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),\n int128 liquidityNet;\n // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint256 feeGrowthOutside0X128;\n uint256 feeGrowthOutside1X128;\n // the cumulative tick value on the other side of the tick\n int56 tickCumulativeOutside;\n // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint160 secondsPerLiquidityOutsideX128;\n // the seconds spent on the other side of the tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint32 secondsOutside;\n // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0\n // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks\n bool initialized;\n }\n\n /// @notice Derives max liquidity per tick from given tick spacing\n /// @dev Executed within the pool constructor\n /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`\n /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...\n /// @return The max liquidity per tick\n function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {\n int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;\n int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;\n uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;\n return type(uint128).max / numTicks;\n }\n\n /// @notice Retrieves fee growth data\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param tickCurrent The current tick\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function getFeeGrowthInside(\n mapping(int24 => Tick.Info) storage self,\n int24 tickLower,\n int24 tickUpper,\n int24 tickCurrent,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128\n ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {\n Info storage lower = self[tickLower];\n Info storage upper = self[tickUpper];\n\n // calculate fee growth below\n uint256 feeGrowthBelow0X128;\n uint256 feeGrowthBelow1X128;\n if (tickCurrent >= tickLower) {\n feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;\n } else {\n feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;\n }\n\n // calculate fee growth above\n uint256 feeGrowthAbove0X128;\n uint256 feeGrowthAbove1X128;\n if (tickCurrent < tickUpper) {\n feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;\n } else {\n feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;\n }\n\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;\n }\n\n /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tick The tick that will be updated\n /// @param tickCurrent The current tick\n /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool\n /// @param time The current block timestamp cast to a uint32\n /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick\n /// @param maxLiquidity The maximum liquidity allocation for a single tick\n /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa\n function update(\n mapping(int24 => Tick.Info) storage self,\n int24 tick,\n int24 tickCurrent,\n int128 liquidityDelta,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time,\n bool upper,\n uint128 maxLiquidity\n ) internal returns (bool flipped) {\n Tick.Info storage info = self[tick];\n\n uint128 liquidityGrossBefore = info.liquidityGross;\n uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);\n\n require(liquidityGrossAfter <= maxLiquidity, 'LO');\n\n flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);\n\n if (liquidityGrossBefore == 0) {\n // by convention, we assume that all growth before a tick was initialized happened _below_ the tick\n if (tick <= tickCurrent) {\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;\n info.tickCumulativeOutside = tickCumulative;\n info.secondsOutside = time;\n }\n info.initialized = true;\n }\n\n info.liquidityGross = liquidityGrossAfter;\n\n // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)\n info.liquidityNet = upper\n ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()\n : int256(info.liquidityNet).add(liquidityDelta).toInt128();\n }\n\n /// @notice Clears tick data\n /// @param self The mapping containing all initialized tick information for initialized ticks\n /// @param tick The tick that will be cleared\n function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {\n delete self[tick];\n }\n\n /// @notice Transitions to next tick as needed by price movement\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tick The destination tick of the transition\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity\n /// @param time The current block.timestamp\n /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function cross(\n mapping(int24 => Tick.Info) storage self,\n int24 tick,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time\n ) internal returns (int128 liquidityNet) {\n Tick.Info storage info = self[tick];\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;\n info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;\n info.secondsOutside = time - info.secondsOutside;\n liquidityNet = info.liquidityNet;\n }\n}\n"
},
"contracts/libraries/TickBitmap.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './BitMath.sol';\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary TickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(tick % 256);\n }\n\n /// @notice Flips the initialized state for a given tick from false to true, or vice versa\n /// @param self The mapping in which to flip the tick\n /// @param tick The tick to flip\n /// @param tickSpacing The spacing between usable ticks\n function flipTick(\n mapping(int16 => uint256) storage self,\n int24 tick,\n int24 tickSpacing\n ) internal {\n require(tick % tickSpacing == 0); // ensure that the tick is spaced\n (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);\n uint256 mask = 1 << bitPos;\n self[wordPos] ^= mask;\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param self The mapping in which to compute the next initialized tick\n /// @param tick The starting tick\n /// @param tickSpacing The spacing between usable ticks\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(\n mapping(int16 => uint256) storage self,\n int24 tick,\n int24 tickSpacing,\n bool lte\n ) internal view returns (int24 next, bool initialized) {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = self[wordPos] & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing\n : (compressed - int24(bitPos)) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = self[wordPos] & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing\n : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;\n }\n }\n}\n"
},
"contracts/libraries/Position.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './FixedPoint128.sol';\nimport './LiquidityMath.sol';\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n // info stored for each user's position\n struct Info {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n // the fees owed to the position owner in token0/token1\n uint128 tokensOwed0;\n uint128 tokensOwed1;\n }\n\n /// @notice Returns the Info struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @return position The position info struct of the given owners' position\n function get(\n mapping(bytes32 => Info) storage self,\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (Position.Info storage position) {\n position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))];\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function update(\n Info storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal {\n Info memory _self = self;\n\n uint128 liquidityNext;\n if (liquidityDelta == 0) {\n require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions\n liquidityNext = _self.liquidity;\n } else {\n liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees\n uint128 tokensOwed0 =\n uint128(\n FullMath.mulDiv(\n feeGrowthInside0X128 - _self.feeGrowthInside0LastX128,\n _self.liquidity,\n FixedPoint128.Q128\n )\n );\n uint128 tokensOwed1 =\n uint128(\n FullMath.mulDiv(\n feeGrowthInside1X128 - _self.feeGrowthInside1LastX128,\n _self.liquidity,\n FixedPoint128.Q128\n )\n );\n\n // update the position\n if (liquidityDelta != 0) self.liquidity = liquidityNext;\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n if (tokensOwed0 > 0 || tokensOwed1 > 0) {\n // overflow is acceptable, have to withdraw before you hit type(uint128).max fees\n self.tokensOwed0 += tokensOwed0;\n self.tokensOwed1 += tokensOwed1;\n }\n }\n}\n"
},
"contracts/libraries/Oracle.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\n/// @title Oracle\n/// @notice Provides price and liquidity data useful for a wide variety of system designs\n/// @dev Instances of stored oracle data, \"observations\", are collected in the oracle array\n/// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the\n/// maximum length of the oracle array. New slots will be added when the array is fully populated.\n/// Observations are overwritten when the full length of the oracle array is populated.\n/// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()\nlibrary Oracle {\n struct Observation {\n // the block timestamp of the observation\n uint32 blockTimestamp;\n // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized\n int56 tickCumulative;\n // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized\n uint160 secondsPerLiquidityCumulativeX128;\n // whether or not the observation is initialized\n bool initialized;\n }\n\n /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values\n /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows\n /// @param last The specified observation to be transformed\n /// @param blockTimestamp The timestamp of the new observation\n /// @param tick The active tick at the time of the new observation\n /// @param liquidity The total in-range liquidity at the time of the new observation\n /// @return Observation The newly populated observation\n function transform(\n Observation memory last,\n uint32 blockTimestamp,\n int24 tick,\n uint128 liquidity\n ) private pure returns (Observation memory) {\n uint32 delta = blockTimestamp - last.blockTimestamp;\n return\n Observation({\n blockTimestamp: blockTimestamp,\n tickCumulative: last.tickCumulative + int56(tick) * delta,\n secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +\n ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),\n initialized: true\n });\n }\n\n /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array\n /// @param self The stored oracle array\n /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32\n /// @return cardinality The number of populated elements in the oracle array\n /// @return cardinalityNext The new length of the oracle array, independent of population\n function initialize(Observation[65535] storage self, uint32 time)\n internal\n returns (uint16 cardinality, uint16 cardinalityNext)\n {\n self[0] = Observation({\n blockTimestamp: time,\n tickCumulative: 0,\n secondsPerLiquidityCumulativeX128: 0,\n initialized: true\n });\n return (1, 1);\n }\n\n /// @notice Writes an oracle observation to the array\n /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.\n /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality\n /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.\n /// @param self The stored oracle array\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param blockTimestamp The timestamp of the new observation\n /// @param tick The active tick at the time of the new observation\n /// @param liquidity The total in-range liquidity at the time of the new observation\n /// @param cardinality The number of populated elements in the oracle array\n /// @param cardinalityNext The new length of the oracle array, independent of population\n /// @return indexUpdated The new index of the most recently written element in the oracle array\n /// @return cardinalityUpdated The new cardinality of the oracle array\n function write(\n Observation[65535] storage self,\n uint16 index,\n uint32 blockTimestamp,\n int24 tick,\n uint128 liquidity,\n uint16 cardinality,\n uint16 cardinalityNext\n ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {\n Observation memory last = self[index];\n\n // early return if we've already written an observation this block\n if (last.blockTimestamp == blockTimestamp) return (index, cardinality);\n\n // if the conditions are right, we can bump the cardinality\n if (cardinalityNext > cardinality && index == (cardinality - 1)) {\n cardinalityUpdated = cardinalityNext;\n } else {\n cardinalityUpdated = cardinality;\n }\n\n indexUpdated = (index + 1) % cardinalityUpdated;\n self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);\n }\n\n /// @notice Prepares the oracle array to store up to `next` observations\n /// @param self The stored oracle array\n /// @param current The current next cardinality of the oracle array\n /// @param next The proposed next cardinality which will be populated in the oracle array\n /// @return next The next cardinality which will be populated in the oracle array\n function grow(\n Observation[65535] storage self,\n uint16 current,\n uint16 next\n ) internal returns (uint16) {\n require(current > 0, 'I');\n // no-op if the passed next value isn't greater than the current next value\n if (next <= current) return current;\n // store in each slot to prevent fresh SSTOREs in swaps\n // this data will not be used because the initialized boolean is still false\n for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;\n return next;\n }\n\n /// @notice comparator for 32-bit timestamps\n /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time\n /// @param time A timestamp truncated to 32 bits\n /// @param a A comparison timestamp from which to determine the relative position of `time`\n /// @param b From which to determine the relative position of `time`\n /// @return bool Whether `a` is chronologically <= `b`\n function lte(\n uint32 time,\n uint32 a,\n uint32 b\n ) private pure returns (bool) {\n // if there hasn't been overflow, no need to adjust\n if (a <= time && b <= time) return a <= b;\n\n uint256 aAdjusted = a > time ? a : a + 2**32;\n uint256 bAdjusted = b > time ? b : b + 2**32;\n\n return aAdjusted <= bAdjusted;\n }\n\n /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.\n /// The result may be the same observation, or adjacent observations.\n /// @dev The answer must be contained in the array, used when the target is located within the stored observation\n /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param target The timestamp at which the reserved observation should be for\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param cardinality The number of populated elements in the oracle array\n /// @return beforeOrAt The observation recorded before, or at, the target\n /// @return atOrAfter The observation recorded at, or after, the target\n function binarySearch(\n Observation[65535] storage self,\n uint32 time,\n uint32 target,\n uint16 index,\n uint16 cardinality\n ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n uint256 l = (index + 1) % cardinality; // oldest observation\n uint256 r = l + cardinality - 1; // newest observation\n uint256 i;\n while (true) {\n i = (l + r) / 2;\n\n beforeOrAt = self[i % cardinality];\n\n // we've landed on an uninitialized tick, keep searching higher (more recently)\n if (!beforeOrAt.initialized) {\n l = i + 1;\n continue;\n }\n\n atOrAfter = self[(i + 1) % cardinality];\n\n bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);\n\n // check if we've found the answer!\n if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;\n\n if (!targetAtOrAfter) r = i - 1;\n else l = i + 1;\n }\n }\n\n /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied\n /// @dev Assumes there is at least 1 initialized observation.\n /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param target The timestamp at which the reserved observation should be for\n /// @param tick The active tick at the time of the returned or simulated observation\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The total pool liquidity at the time of the call\n /// @param cardinality The number of populated elements in the oracle array\n /// @return beforeOrAt The observation which occurred at, or before, the given timestamp\n /// @return atOrAfter The observation which occurred at, or after, the given timestamp\n function getSurroundingObservations(\n Observation[65535] storage self,\n uint32 time,\n uint32 target,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n // optimistically set before to the newest observation\n beforeOrAt = self[index];\n\n // if the target is chronologically at or after the newest observation, we can early return\n if (lte(time, beforeOrAt.blockTimestamp, target)) {\n if (beforeOrAt.blockTimestamp == target) {\n // if newest observation equals target, we're in the same block, so we can ignore atOrAfter\n return (beforeOrAt, atOrAfter);\n } else {\n // otherwise, we need to transform\n return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));\n }\n }\n\n // now, set before to the oldest observation\n beforeOrAt = self[(index + 1) % cardinality];\n if (!beforeOrAt.initialized) beforeOrAt = self[0];\n\n // ensure that the target is chronologically at or after the oldest observation\n require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');\n\n // if we've reached this point, we have to binary search\n return binarySearch(self, time, target, index, cardinality);\n }\n\n /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.\n /// 0 may be passed as `secondsAgo' to return the current cumulative values.\n /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values\n /// at exactly the timestamp between the two observations.\n /// @param self The stored oracle array\n /// @param time The current block timestamp\n /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation\n /// @param tick The current tick\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The current in-range pool liquidity\n /// @param cardinality The number of populated elements in the oracle array\n /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`\n /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`\n function observeSingle(\n Observation[65535] storage self,\n uint32 time,\n uint32 secondsAgo,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {\n if (secondsAgo == 0) {\n Observation memory last = self[index];\n if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity);\n return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);\n }\n\n uint32 target = time - secondsAgo;\n\n (Observation memory beforeOrAt, Observation memory atOrAfter) =\n getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);\n\n if (target == beforeOrAt.blockTimestamp) {\n // we're at the left boundary\n return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);\n } else if (target == atOrAfter.blockTimestamp) {\n // we're at the right boundary\n return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);\n } else {\n // we're in the middle\n uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;\n uint32 targetDelta = target - beforeOrAt.blockTimestamp;\n return (\n beforeOrAt.tickCumulative +\n ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *\n targetDelta,\n beforeOrAt.secondsPerLiquidityCumulativeX128 +\n uint160(\n (uint256(\n atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128\n ) * targetDelta) / observationTimeDelta\n )\n );\n }\n }\n\n /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`\n /// @dev Reverts if `secondsAgos` > oldest observation\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation\n /// @param tick The current tick\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The current in-range pool liquidity\n /// @param cardinality The number of populated elements in the oracle array\n /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`\n /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`\n function observe(\n Observation[65535] storage self,\n uint32 time,\n uint32[] memory secondsAgos,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {\n require(cardinality > 0, 'I');\n\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle(\n self,\n time,\n secondsAgos[i],\n tick,\n index,\n liquidity,\n cardinality\n );\n }\n }\n}\n"
},
"contracts/libraries/FullMath.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n function mulDiv(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n // 512-bit multiply [prod1 prod0] = a * b\n // Compute the product mod 2**256 and mod 2**256 - 1\n // then use the Chinese Remainder Theorem to reconstruct\n // the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2**256 + prod0\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(a, b, not(0))\n prod0 := mul(a, b)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n require(denominator > 0);\n assembly {\n result := div(prod0, denominator)\n }\n return result;\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0]\n // Compute remainder using mulmod\n uint256 remainder;\n assembly {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly {\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator\n // Compute largest power of two divisor of denominator.\n // Always >= 1.\n uint256 twos = -denominator & denominator;\n // Divide denominator by power of two\n assembly {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly {\n prod0 := div(prod0, twos)\n }\n // Shift in bits from prod1 into prod0. For this we need\n // to flip `twos` such that it is 2**256 / twos.\n // If twos is zero, then it becomes one\n assembly {\n twos := add(div(sub(0, twos), twos), 1)\n }\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2**256\n // Now that denominator is an odd number, it has an inverse\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n // Compute the inverse by starting with a seed that is correct\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\n uint256 inv = (3 * denominator) ^ 2;\n // Now use Newton-Raphson iteration to improve the precision.\n // Thanks to Hensel's lifting lemma, this also works in modular\n // arithmetic, doubling the correct bits in each step.\n inv *= 2 - denominator * inv; // inverse mod 2**8\n inv *= 2 - denominator * inv; // inverse mod 2**16\n inv *= 2 - denominator * inv; // inverse mod 2**32\n inv *= 2 - denominator * inv; // inverse mod 2**64\n inv *= 2 - denominator * inv; // inverse mod 2**128\n inv *= 2 - denominator * inv; // inverse mod 2**256\n\n // Because the division is now exact we can divide by multiplying\n // with the modular inverse of denominator. This will give us the\n // correct result modulo 2**256. Since the precoditions guarantee\n // that the outcome is less than 2**256, this is the final result.\n // We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inv;\n return result;\n }\n\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n function mulDivRoundingUp(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) > 0) {\n require(result < type(uint256).max);\n result++;\n }\n }\n}\n"
},
"contracts/libraries/FixedPoint128.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n"
},
"contracts/libraries/TransferHelper.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../interfaces/IERC20Minimal.sol';\n\n/// @title TransferHelper\n/// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false\nlibrary TransferHelper {\n /// @notice Transfers tokens from msg.sender to a recipient\n /// @dev Calls transfer on token contract, errors with TF if transfer fails\n /// @param token The contract address of the token which will be transferred\n /// @param to The recipient of the transfer\n /// @param value The value of the transfer\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) =\n token.call(abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');\n }\n}\n"
},
"contracts/libraries/TickMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n int24 internal constant MIN_TICK = -887272;\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n int24 internal constant MAX_TICK = -MIN_TICK;\n\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\n /// @dev Throws if |tick| > max tick\n /// @param tick The input tick for the above formula\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n /// at the given tick\n function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n require(absTick <= uint256(MAX_TICK), 'T');\n\n uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n if (tick > 0) ratio = type(uint256).max / ratio;\n\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n }\n\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n /// ever return.\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n // second inequality must be < because the price can never reach the price at the max tick\n require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');\n uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n uint256 r = ratio;\n uint256 msb = 0;\n\n assembly {\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(5, gt(r, 0xFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(4, gt(r, 0xFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(3, gt(r, 0xFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(2, gt(r, 0xF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(1, gt(r, 0x3))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := gt(r, 0x1)\n msb := or(msb, f)\n }\n\n if (msb >= 128) r = ratio >> (msb - 127);\n else r = ratio << (127 - msb);\n\n int256 log_2 = (int256(msb) - 128) << 64;\n\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(63, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(62, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(61, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(60, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(59, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(58, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(57, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(56, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(55, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(54, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(53, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(52, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(51, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(50, f))\n }\n\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n }\n}\n"
},
"contracts/libraries/LiquidityMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}\n"
},
"contracts/libraries/SqrtPriceMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}\n"
},
"contracts/libraries/SwapMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\n }\n }\n}\n"
},
"contracts/interfaces/IUniswapV3PoolDeployer.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title An interface for a contract that is capable of deploying Uniswap V3 Pools\n/// @notice A contract that constructs a pool must implement this to pass arguments to the pool\n/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash\n/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain\ninterface IUniswapV3PoolDeployer {\n /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.\n /// @dev Called by the pool constructor to fetch the parameters of the pool\n /// Returns factory The factory address\n /// Returns token0 The first token of the pool by address sort order\n /// Returns token1 The second token of the pool by address sort order\n /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// Returns tickSpacing The minimum number of ticks between initialized ticks\n function parameters()\n external\n view\n returns (\n address factory,\n address token0,\n address token1,\n uint24 fee,\n int24 tickSpacing\n );\n}\n"
},
"contracts/interfaces/IUniswapV3Factory.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n /// @notice Emitted when the owner of the factory is changed\n /// @param oldOwner The owner before the owner was changed\n /// @param newOwner The owner after the owner was changed\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n /// @notice Emitted when a pool is created\n /// @param token0 The first token of the pool by address sort order\n /// @param token1 The second token of the pool by address sort order\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks\n /// @param pool The address of the created pool\n event PoolCreated(\n address indexed token0,\n address indexed token1,\n uint24 indexed fee,\n int24 tickSpacing,\n address pool\n );\n\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n /// @param fee The enabled fee, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n /// @notice Returns the current owner of the factory\n /// @dev Can be changed by the current owner via setOwner\n /// @return The address of the factory owner\n function owner() external view returns (address);\n\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n /// @return The tick spacing\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The pool address\n function getPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external view returns (address pool);\n\n /// @notice Creates a pool for the given two tokens and fee\n /// @param tokenA One of the two tokens in the desired pool\n /// @param tokenB The other of the two tokens in the desired pool\n /// @param fee The desired fee for the pool\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n /// are invalid.\n /// @return pool The address of the newly created pool\n function createPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external returns (address pool);\n\n /// @notice Updates the owner of the factory\n /// @dev Must be called by the current owner\n /// @param _owner The new owner of the factory\n function setOwner(address _owner) external;\n\n /// @notice Enables a fee amount with the given tickSpacing\n /// @dev Fee amounts may never be removed once enabled\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n"
},
"contracts/interfaces/IERC20Minimal.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/interfaces/callback/IUniswapV3MintCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#mint\n/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface\ninterface IUniswapV3MintCallback {\n /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.\n /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity\n /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call\n function uniswapV3MintCallback(\n uint256 amount0Owed,\n uint256 amount1Owed,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/callback/IUniswapV3SwapCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/callback/IUniswapV3FlashCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#flash\n/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface\ninterface IUniswapV3FlashCallback {\n /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.\n /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param fee0 The fee amount in token0 due to the pool by the end of the flash\n /// @param fee1 The fee amount in token1 due to the pool by the end of the flash\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolImmutables.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n /// @return The contract address\n function factory() external view returns (address);\n\n /// @notice The first of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token0() external view returns (address);\n\n /// @notice The second of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token1() external view returns (address);\n\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n /// @return The fee\n function fee() external view returns (uint24);\n\n /// @notice The pool tick spacing\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n /// This value is an int24 to avoid casting even though it is always positive.\n /// @return The tick spacing\n function tickSpacing() external view returns (int24);\n\n /// @notice The maximum amount of position liquidity that can use any tick in the range\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n /// @return The max amount of liquidity per tick\n function maxLiquidityPerTick() external view returns (uint128);\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n /// when accessed externally.\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n /// boundary.\n /// observationIndex The index of the last oracle observation that was written,\n /// observationCardinality The current maximum number of observations stored in the pool,\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n /// feeProtocol The protocol fee for both tokens of the pool.\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n /// unlocked Whether the pool is currently locked to reentrancy\n function slot0()\n external\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n uint16 observationCardinalityNext,\n uint8 feeProtocol,\n bool unlocked\n );\n\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal0X128() external view returns (uint256);\n\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal1X128() external view returns (uint256);\n\n /// @notice The amounts of token0 and token1 that are owed to the protocol\n /// @dev Protocol fees will never exceed uint128 max in either token\n function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n /// @notice The currently in range liquidity available to the pool\n /// @dev This value has no relationship to the total liquidity across all ticks\n function liquidity() external view returns (uint128);\n\n /// @notice Look up information about a specific tick in the pool\n /// @param tick The tick to look up\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n /// tick upper,\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n /// a specific position.\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128,\n int56 tickCumulativeOutside,\n uint160 secondsPerLiquidityOutsideX128,\n uint32 secondsOutside,\n bool initialized\n );\n\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n /// @notice Returns the information about a position by the position's key\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n /// @return _liquidity The amount of liquidity in the position,\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 _liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n\n /// @notice Returns data about a specific observation index\n /// @param index The element of the observations array to fetch\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n /// ago, rather than at a specific index in the array.\n /// @return blockTimestamp The timestamp of the observation,\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n /// Returns initialized whether the observation has been initialized and the values are safe to use\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulativeX128,\n bool initialized\n );\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n /// you must call it with secondsAgos = [3600, 0].\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n /// timestamp\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n /// snapshot is taken and the second snapshot is taken.\n /// @param tickLower The lower tick of the range\n /// @param tickUpper The upper tick of the range\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n /// @return secondsInside The snapshot of seconds per liquidity for the range\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n );\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n /// @notice Sets the initial price for the pool\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n function initialize(uint160 sqrtPriceX96) external;\n\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n /// @param recipient The address for which the liquidity will be created\n /// @param tickLower The lower tick of the position in which to add liquidity\n /// @param tickUpper The upper tick of the position in which to add liquidity\n /// @param amount The amount of liquidity to mint\n /// @param data Any data that should be passed through to the callback\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Collects tokens owed to a position\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n /// @param recipient The address which should receive the fees collected\n /// @param tickLower The lower tick of the position for which to collect fees\n /// @param tickUpper The upper tick of the position for which to collect fees\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n /// @dev Fees must be collected separately via a call to #collect\n /// @param tickLower The lower tick of the position for which to burn liquidity\n /// @param tickUpper The upper tick of the position for which to burn liquidity\n /// @param amount How much liquidity to burn\n /// @return amount0 The amount of token0 sent to the recipient\n /// @return amount1 The amount of token1 sent to the recipient\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Swap token0 for token1, or token1 for token0\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n /// @param recipient The address to receive the output of the swap\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n /// @param data Any data to be passed through to the callback\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n /// @param recipient The address which will receive the token0 and token1 amounts\n /// @param amount0 The amount of token0 to send\n /// @param amount1 The amount of token1 to send\n /// @param data Any data to be passed through to the callback\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n /// the input observationCardinalityNext.\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n /// @notice Set the denominator of the protocol's % share of the fees\n /// @param feeProtocol0 new protocol fee for token0 of the pool\n /// @param feeProtocol1 new protocol fee for token1 of the pool\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n /// @notice Collect the protocol fee accrued to the pool\n /// @param recipient The address to which collected protocol fees should be sent\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n /// @return amount0 The protocol fee collected in token0\n /// @return amount1 The protocol fee collected in token1\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n /// @notice Emitted when liquidity is minted for a given position\n /// @param sender The address that minted the liquidity\n /// @param owner The owner of the position and recipient of any minted liquidity\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity minted to the position range\n /// @param amount0 How much token0 was required for the minted liquidity\n /// @param amount1 How much token1 was required for the minted liquidity\n event Mint(\n address sender,\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when fees are collected by the owner of a position\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n /// @param owner The owner of the position for which fees are collected\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount0 The amount of token0 fees collected\n /// @param amount1 The amount of token1 fees collected\n event Collect(\n address indexed owner,\n address recipient,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount0,\n uint128 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n /// @param owner The owner of the position for which liquidity is removed\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity to remove\n /// @param amount0 The amount of token0 withdrawn\n /// @param amount1 The amount of token1 withdrawn\n event Burn(\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted by the pool for any swaps between token0 and token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the output of the swap\n /// @param amount0 The delta of the token0 balance of the pool\n /// @param amount1 The delta of the token1 balance of the pool\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n /// @param liquidity The liquidity of the pool after the swap\n /// @param tick The log base 1.0001 of price of the pool after the swap\n event Swap(\n address indexed sender,\n address indexed recipient,\n int256 amount0,\n int256 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick\n );\n\n /// @notice Emitted by the pool for any flashes of token0/token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the tokens from flash\n /// @param amount0 The amount of token0 that was flashed\n /// @param amount1 The amount of token1 that was flashed\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n event Flash(\n address indexed sender,\n address indexed recipient,\n uint256 amount0,\n uint256 amount1,\n uint256 paid0,\n uint256 paid1\n );\n\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n /// just before a mint/swap/burn.\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n event IncreaseObservationCardinalityNext(\n uint16 observationCardinalityNextOld,\n uint16 observationCardinalityNextNew\n );\n\n /// @notice Emitted when the protocol fee is changed by the pool\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\n /// @param feeProtocol0New The updated value of the token0 protocol fee\n /// @param feeProtocol1New The updated value of the token1 protocol fee\n event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n /// @param sender The address that collects the protocol fees\n /// @param recipient The address that receives the collected protocol fees\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\n event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
},
"contracts/libraries/BitMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\n }\n}\n"
},
"contracts/libraries/UnsafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}\n"
},
"contracts/libraries/FixedPoint96.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n uint8 internal constant RESOLUTION = 96;\n uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 800
},
"metadata": {
"bytecodeHash": "none"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,499,971 |
c6cd826d4f3923ce8560ef7dc8409fd53c32991189d0959ef67440e2d4f26399
|
5aff627cc809ae1e1392b63a4b3550b892a2c675c80b84937c2414fe212cd78d
|
d4d1e6defc6ea4db99ffbd9c488e0efdf9e3ce91
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
c70c7090b91e0d9861d734eb613761e8b35224d2
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,499,973 |
21e4c8cbe9e18c06309aac67ef0fb551d4a80caa9b20e841cf2346f9adb6e661
|
1052b734135ec455f978c75e1369f1fe9d7d88ac22b098ef328eedcaa37c8be9
|
302ff8c5d83fde0044c6625cb2ff122112257595
|
302ff8c5d83fde0044c6625cb2ff122112257595
|
b5719cc29184307ec05cffed0b0c8c85c90a8e44
|
608060405234801561001057600080fd5b50610160806100206000396000f3fe6080604052600436106100225760003560e01c806392483c341461002e57610029565b3661002957005b600080fd5b610048600480360381019061004391906100fd565b61004a565b005b60008190508073ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f19350505050158015610095573d6000803e3d6000fd5b505050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006100ca8261009f565b9050919050565b6100da816100bf565b81146100e557600080fd5b50565b6000813590506100f7816100d1565b92915050565b6000602082840312156101135761011261009a565b5b6000610121848285016100e8565b9150509291505056fea2646970667358221220932f87cc45fbf4293d24dc1d8a4c7427d98b6d0b184564c81606da22e1b24d7464736f6c63430008090033
|
6080604052600436106100225760003560e01c806392483c341461002e57610029565b3661002957005b600080fd5b610048600480360381019061004391906100fd565b61004a565b005b60008190508073ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f19350505050158015610095573d6000803e3d6000fd5b505050565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006100ca8261009f565b9050919050565b6100da816100bf565b81146100e557600080fd5b50565b6000813590506100f7816100d1565b92915050565b6000602082840312156101135761011261009a565b5b6000610121848285016100e8565b9150509291505056fea2646970667358221220932f87cc45fbf4293d24dc1d8a4c7427d98b6d0b184564c81606da22e1b24d7464736f6c63430008090033
| |
1 | 19,499,973 |
21e4c8cbe9e18c06309aac67ef0fb551d4a80caa9b20e841cf2346f9adb6e661
|
9dd0de1ad8f157bd09a58f6d32c37ea5b4363c43786973cb07a9da107fef97eb
|
865446eae99bd35f2cb04d1aff5cfb33d9f7c10b
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
55ecf5e00152170bd09591f05beade06a064605a
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,499,975 |
95af77b422addaad562fcb87645fa2fd823099cf0e11c09d2fea619c6d05530b
|
172dbef2d6a5442326de031ddb248c55046a6cc6f94c7ef8531df51c82435d43
|
a9a0b8a5e1adca0caccc63a168f053cd3be30808
|
01cd62ed13d0b666e2a10d13879a763dfd1dab99
|
1278c5374e3ae90c24bdc8afa43dbba4f91e535d
|
3d602d80600a3d3981f3363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
b145e63cbe2153a5ee6b8b7a08dc51a308a667b3
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
632e4b07eddda3c403d31f8a7ba5da954d00d9ce
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
e3c7943f6bf6870f49f8742f8d8cfc0a4f29cf51
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
2e5c4ee994f383948f17fcef033e87b3ce782b4b
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
6a78c5e72dd4fb053ad397db657e9bdee7464c73
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
36eef4ee1d78d9c57dc2508c80c1b0a0a773dafc
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
a8c71af56bf2cd04849a2923077579444363d7b8
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
dd24de1b7d3ad94f75b35fdb4df6c53baf3cc03b
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
fde29dde1ab4cdaf4cd7cf4f3916f8fb2e76fc97
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
3c1a137e5c5512ab1a508f611cebb6e546e56c38
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
1480a97410bd64a52400aa0037b63d80c89e4103
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
de9175c5c1b7a63bb177bc7ed4ebad0e7bb68452
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
c47a91d692085a85eeeae6afa5ff62d9546384e3
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
ab88f057a9138b380f4baef75a7564530ad4aebb
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
6061d88093f93cbea84b0cccf4d0cd61f7d4ad2b
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
5d22c830206ee351053867f8812f8695dda83faa
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
3e186c063cf49106fe0dd2faac0d4d7c841b8a90
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
093f85a09fa5ed11aee6dd1b843d9e5467984f07
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
0ddfb5f9d9c268bc3a757cd22885dc0f042a302e
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
add71c4404cfb4dbc36b047256a53feeea1f6571
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
2ca7102b8c30106e242028be770d64f15c68090a
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
b89e74e685d364ef81f2b4f535546279e58fee7f
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
db810019aa06a88da7a4645dadd75df4913f3934
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
032f126caffd81feb6aeacd1aa1ca6a262268f37
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
ae704f9857a306c753a428c9500fd0e72bc28a6b
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
a9c47b63ee19737ff90371c25160d0ac0cc4ada7
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
0be3cdd3995449d6105eec3f697cd217e9ce52dc
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
ec6378436c5e13df77443b49e78111be54b597e1
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
1581efd09941b5508f6ffd20c2b295b50d5b4768
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
89ce02665440492cbb4dd4b2ed86af810f2e2ced
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,499,976 |
b4bc31b8d3815d5f6ed04b0ba1eb82d3ea7e1266ff0e58ac9a08a9eaa9f40158
|
e8f7580d96f3c0d7e554bc684ca9c65c665bfcba17c59a4aa53eae227bd61781
|
3afe6438e7c3ba411cea2e923d72c2149a20802a
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
235c729804ad87f27e50cc3398b8d8f9b7715ffa
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.