文件 1 的 35:Address.sol
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
文件 2 的 35:Community.sol
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./FurLib.sol";
contract Community is ERC20 {
mapping(address => address) private _delegates;
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
constructor() ERC20("FurballsCommunity", "FBLS") { }
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
mapping(address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)');
bytes32 public constant DELEGATION_TYPEHASH =
keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)');
mapping(address => uint256) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
function votesToDelegate(address delegator) public view returns (uint96) {
return safe96(balanceOf(delegator), 'Community::votesToDelegate: amount exceeds 96 bits');
}
function delegates(address delegator) public view returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
function update(FurLib.Account memory account, address addr) external returns (uint256) {
require(false, 'NEED SECURITY');
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
require(from == address(0), "Votes may not be traded.");
_moveDelegates(delegates(from), delegates(to), uint96(amount));
}
function delegate(address delegatee) public {
if (delegatee == address(0)) delegatee = msg.sender;
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'Community::delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'Community::delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, 'Community::getPriorVotes: not yet determined');
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
uint96 amount = votesToDelegate(delegator);
_moveDelegates(currentDelegate, delegatee, amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, 'Community::_moveDelegates: amount underflows');
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, 'Community::_moveDelegates: amount overflows');
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
'Community::_writeCheckpoint: block number exceeds 32 bits'
);
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
文件 3 的 35:Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
文件 4 的 35:Counters.sol
pragma solidity ^0.8.0;
library Counters {
struct Counter {
uint256 _value;
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
文件 5 的 35:Dice.sol
pragma solidity ^0.8.6;
import "./FurLib.sol";
abstract contract Dice {
uint32 private LAST = 0;
function roll(uint32 seed) public returns (uint32) {
LAST = uint32(uint256(keccak256(
abi.encodePacked(block.timestamp, block.basefee, _prng(LAST == 0 ? seed : LAST)))
));
return LAST;
}
function _prng(uint32 seed) internal view returns (uint32) {
uint64 nonce = seed == 0 ? uint32(block.timestamp) : seed;
uint64 product = uint64(nonce) * 48271;
uint32 x = uint32((product % 0x7fffffff) + (product >> 31));
return (x & 0x7fffffff) + (x >> 31);
}
}
文件 6 的 35:ECDSA.sol
pragma solidity ^0.8.0;
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return;
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
文件 7 的 35:ERC165.sol
pragma solidity ^0.8.0;
import "./IERC165.sol";
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
文件 8 的 35:ERC20.sol
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
文件 9 的 35:ERC721.sol
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
文件 10 的 35:ERC721Enumerable.sol
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
文件 11 的 35:EngineA.sol
pragma solidity ^0.8.6;
import "./LootEngine.sol";
contract EngineA is LootEngine {
constructor(address furballs, address tradeProxy, address companyProxy)
LootEngine(furballs, tradeProxy, companyProxy) { }
}
文件 12 的 35:Fur.sol
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./Furballs.sol";
import "./editions/IFurballEdition.sol";
import "./utils/FurProxy.sol";
contract Fur is ERC20, FurProxy {
mapping(uint256 => FurLib.Snack[]) public _snacks;
uint256 private _intervalDuration;
constructor(address furballsAddress) FurProxy(furballsAddress) ERC20("Fur", "FUR") {
_intervalDuration = furballs.intervalDuration();
}
function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) {
return _snacks[tokenId];
}
function cleanSnacks(uint256 tokenId) public returns (uint256) {
if (_snacks[tokenId].length == 0) return 0;
return _cleanSnack(tokenId, 0);
}
function snackEffects(uint256 tokenId) external view returns(uint256) {
uint16 hap = 0;
uint16 en = 0;
for (uint32 i=0; i<_snacks[tokenId].length && i <= FurLib.Max32; i++) {
uint256 remaining = _snackTimeRemaning(_snacks[tokenId][i]);
if (remaining > 0) {
hap += _snacks[tokenId][i].happiness;
en += _snacks[tokenId][i].energy;
}
}
return (hap * 0x10000) + (en);
}
function earn(address addr, uint256 amount) external gameAdmin {
if (amount == 0) return;
_mint(addr, amount);
}
function spend(address addr, uint256 amount) external gameAdmin {
_burn(addr, amount);
}
function purchaseMint(
address from, uint8 permissions, address to, IFurballEdition edition
) external gameAdmin returns (bool) {
require(edition.maxMintable(to) > 0, "LIVE");
uint32 cnt = edition.count();
uint32 adoptable = edition.maxAdoptable();
bool requiresPurchase = cnt >= adoptable;
if (requiresPurchase) {
_gift(from, permissions, to, edition.purchaseFur());
}
return requiresPurchase;
}
function purchaseUpgrade(
FurLib.RewardModifiers memory modifiers,
address from, uint8 permissions, uint256 tokenId, uint128 lootId, uint8 chances
) external gameAdmin returns(uint128) {
address owner = furballs.ownerOf(tokenId);
_gift(from, permissions, owner, 500 * uint256(chances));
return furballs.engine().upgradeLoot(modifiers, owner, lootId, chances);
}
function purchaseSnack(
address from, uint8 permissions, uint256 tokenId, uint32 snackId, uint16 count
) external gameAdmin {
FurLib.Snack memory snack = furballs.engine().getSnack(snackId);
require(snack.count > 0, "COUNT");
require(snack.fed == 0, "FED");
_gift(from, permissions, furballs.ownerOf(tokenId), snack.furCost * count);
uint256 snackData = _cleanSnack(tokenId, snack.snackId);
uint32 existingSnackNumber = uint32(snackData / 0x100000000);
snack.count *= count;
if (existingSnackNumber > 0) {
_snacks[tokenId][existingSnackNumber - 1].count += snack.count;
} else {
snack.fed = uint64(block.timestamp);
_snacks[tokenId].push(snack);
}
}
function _cleanSnack(uint256 tokenId, uint32 snackId) internal returns(uint256) {
uint32 ret = 0;
uint16 hap = 0;
uint16 en = 0;
for (uint32 i=1; i<=_snacks[tokenId].length && i <= FurLib.Max32; i++) {
FurLib.Snack memory snack = _snacks[tokenId][i-1];
if (_snackTimeRemaning(snack) == 0) {
if (_snacks[tokenId].length > 1) {
_snacks[tokenId][i-1] = _snacks[tokenId][_snacks[tokenId].length - 1];
}
_snacks[tokenId].pop();
i--;
continue;
}
hap += snack.happiness;
en += snack.energy;
if (snackId != 0 && snack.snackId == snackId) {
ret = i;
}
}
return (ret * 0x100000000) + (hap * 0x10000) + (en);
}
function _snackTimeRemaning(FurLib.Snack memory snack) internal view returns(uint256) {
if (snack.fed == 0) return 0;
uint256 expiresAt = uint256(snack.fed + (snack.count * snack.duration * _intervalDuration));
return expiresAt <= block.timestamp ? 0 : (expiresAt - block.timestamp);
}
function _gift(address from, uint8 permissions, address to, uint256 furCost) internal returns(bool) {
bool isGift = to != from;
require(!isGift || permissions >= FurLib.PERMISSION_ADMIN, "GIFT");
if (!isGift && furCost > 0) {
_burn(from, furCost);
}
return isGift;
}
}
文件 13 的 35:FurDefs.sol
pragma solidity ^0.8.6;
import "./FurLib.sol";
library FurDefs {
function rarityName(uint8 rarity) internal pure returns(string memory) {
if (rarity == 0) return "Common";
if (rarity == 1) return "Elite";
if (rarity == 2) return "Mythic";
if (rarity == 3) return "Legendary";
return "Ultimate";
}
function raritySuffix(uint8 rarity) internal pure returns(string memory) {
return rarity == 0 ? "" : string(abi.encodePacked(" (", rarityName(rarity), ")"));
}
function renderPoints(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 cnt = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<cnt; i++) {
uint16 x = uint8(data[ptr]) * 256 + uint8(data[ptr + 1]);
uint16 y = uint8(data[ptr + 2]) * 256 + uint8(data[ptr + 3]);
points = abi.encodePacked(points, FurLib.uint2str(x), ',', FurLib.uint2str(y), i == (cnt - 1) ? '': ' ');
ptr += 4;
}
return (ptr, abi.encodePacked('points="', points, '" '));
}
function renderTransform(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<len; i++) {
bytes memory point = "";
(ptr, point) = unpackFloat(ptr, data);
points = i == (len - 1) ? abi.encodePacked(points, point) : abi.encodePacked(points, point, ' ');
}
return (ptr, abi.encodePacked('transform="matrix(', points, ')" '));
}
function renderDisplay(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
string[2] memory vals = ['inline', 'none'];
return (ptr + 1, abi.encodePacked('display="', vals[uint8(data[ptr])], '" '));
}
function renderFloat(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[2] memory floatMap = ['opacity', 'offset'];
bytes memory floatVal = "";
(ptr, floatVal) = unpackFloat(ptr + 1, data);
return (ptr, abi.encodePacked(floatMap[propType], '="', floatVal,'" '));
}
function unpackFloat(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 decimals = uint8(data[ptr]);
ptr++;
if (decimals == 0) return (ptr, '0');
uint8 hi = decimals / 16;
uint16 wholeNum = 0;
decimals = decimals % 16;
if (hi >= 10) {
wholeNum = uint16(uint8(data[ptr]) * 256 + uint8(data[ptr + 1]));
ptr += 2;
} else if (hi >= 8) {
wholeNum = uint16(uint8(data[ptr]));
ptr++;
}
if (decimals == 0) return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum)));
bytes memory remainder = new bytes(decimals);
for (uint8 d=0; d<decimals; d+=2) {
remainder[d] = bytes1(48 + uint8(data[ptr] >> 4));
if ((d + 1) < decimals) {
remainder[d+1] = bytes1(48 + uint8(data[ptr] & 0x0f));
}
ptr++;
}
return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum), '.', remainder));
}
function renderInt(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[13] memory intMap = ['cx', 'cy', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'r', 'rx', 'ry', 'width', 'height'];
uint16 val = uint16(uint8(data[ptr + 1]) * 256) + uint8(data[ptr + 2]);
if (val >= 0x8000) {
return (ptr + 3, abi.encodePacked(intMap[propType], '="-', FurLib.uint2str(uint32(0x10000 - val)),'" '));
}
return (ptr + 3, abi.encodePacked(intMap[propType], '="', FurLib.uint2str(val),'" '));
}
function renderStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
string[4] memory strMap = ['id', 'enable-background', 'gradientUnits', 'gradientTransform'];
uint8 t = uint8(data[ptr]);
require(t < 4, 'STR');
bytes memory str = "";
(ptr, str) = unpackStr(ptr + 1, data);
return (ptr, abi.encodePacked(strMap[t], '="', str, '" '));
}
function unpackStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
bytes memory str = bytes(new string(len));
for (uint8 i=0; i<len; i++) {
str[i] = data[ptr + 1 + i];
}
return (ptr + 1 + len, str);
}
}
文件 14 的 35:FurLib.sol
pragma solidity ^0.8.6;
library FurLib {
struct Account {
uint64 created;
uint32 numFurballs;
uint32 maxFurballs;
uint16 maxLevel;
uint16 reputation;
uint16 standing;
uint8 permissions;
}
struct FurballStats {
uint16 expRate;
uint16 furRate;
RewardModifiers modifiers;
Furball definition;
Snack[] snacks;
}
struct Rewards {
uint16 levels;
uint32 experience;
uint32 fur;
uint128 loot;
}
struct Furball {
uint32 number;
uint16 count;
uint16 rarity;
uint32 experience;
uint32 zone;
uint16 level;
uint16 weight;
uint64 birth;
uint64 trade;
uint64 last;
uint32 moves;
uint256[] inventory;
}
struct RewardModifiers {
uint16 expPercent;
uint16 furPercent;
uint16 luckPercent;
uint16 happinessPoints;
uint16 energyPoints;
uint32 zone;
}
struct Snack {
uint32 snackId;
uint32 duration;
uint16 furCost;
uint16 happiness;
uint16 energy;
uint16 count;
uint64 fed;
}
struct Feeding {
uint256 tokenId;
uint32 snackId;
uint16 count;
}
uint32 public constant Max32 = type(uint32).max;
uint8 public constant PERMISSION_USER = 1;
uint8 public constant PERMISSION_MODERATOR = 2;
uint8 public constant PERMISSION_ADMIN = 4;
uint8 public constant PERMISSION_OWNER = 5;
uint8 public constant PERMISSION_CONTRACT = 0x10;
uint32 public constant EXP_PER_INTERVAL = 500;
uint32 public constant FUR_PER_INTERVAL = 100;
uint8 public constant LOOT_BYTE_STAT = 1;
uint8 public constant LOOT_BYTE_RARITY = 2;
uint8 public constant SNACK_BYTE_ENERGY = 0;
uint8 public constant SNACK_BYTE_HAPPINESS = 2;
uint256 public constant OnePercent = 1000;
uint256 public constant OneHundredPercent = 100000;
function bytePower(uint8 byteNum) internal pure returns (uint256) {
if (byteNum == 0) return 0x1;
if (byteNum == 1) return 0x100;
if (byteNum == 2) return 0x10000;
if (byteNum == 3) return 0x1000000;
if (byteNum == 4) return 0x100000000;
if (byteNum == 5) return 0x10000000000;
if (byteNum == 6) return 0x1000000000000;
if (byteNum == 7) return 0x100000000000000;
if (byteNum == 8) return 0x10000000000000000;
if (byteNum == 9) return 0x1000000000000000000;
if (byteNum == 10) return 0x100000000000000000000;
if (byteNum == 11) return 0x10000000000000000000000;
if (byteNum == 12) return 0x1000000000000000000000000;
return (0x100 ** byteNum);
}
function extractBytes(uint value, uint8 startAt, uint8 numBytes) internal pure returns (uint) {
return (value / bytePower(startAt)) % bytePower(numBytes);
}
function expToLevel(uint32 exp, uint32 maxExp) internal pure returns(uint256) {
exp = exp > maxExp ? maxExp : exp;
return sqrt(exp < 100 ? 0 : ((exp + exp - 100) / 100));
}
function sqrt(uint32 x) internal pure returns(uint256) {
if (x < 1) return 0;
if (x < 4) return 1;
uint z = (x + 1) / 2;
uint y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
function bytesHex(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(data.length * 2);
for (uint i = 0; i < data.length; i++) {
str[i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[1 + i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint256 encodedLen = 4 * ((data.length + 2) / 3);
string memory result = new string(encodedLen + 32);
assembly {
mstore(result, encodedLen)
let tablePtr := add(table, 1)
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
let resultPtr := add(result, 32)
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
文件 15 的 35:FurProxy.sol
pragma solidity ^0.8.6;
import "../Furballs.sol";
import "./FurLib.sol";
abstract contract FurProxy {
Furballs public furballs;
constructor(address furballsAddress) {
furballs = Furballs(furballsAddress);
}
function setFurballs(address addr) external onlyOwner {
furballs = Furballs(addr);
}
modifier onlyOwner() {
require(_permissions(msg.sender) >= FurLib.PERMISSION_OWNER, "OWN");
_;
}
modifier gameAdmin() {
require(_permissions(msg.sender) >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
modifier gameModerators() {
require(_permissions(msg.sender) >= FurLib.PERMISSION_MODERATOR, "MOD");
_;
}
modifier onlyFurballs() {
require(msg.sender == address(furballs), "FBL");
_;
}
function _permissions(address addr) internal view returns (uint8) {
uint8 permissions = _userPermissions(addr);
if (permissions > 0) return permissions;
if (addr == address(furballs) ||
addr == address(furballs.engine()) ||
addr == address(furballs.furgreement()) ||
addr == address(furballs.governance()) ||
addr == address(furballs.fur())
) {
return FurLib.PERMISSION_CONTRACT;
}
return 0;
}
function _userPermissions(address addr) internal view returns (uint8) {
if (addr == address(0)) return 0;
uint256 size;
assembly { size := extcodesize(addr) }
if (addr != tx.origin || size != 0) return 0;
if (addr == furballs.owner()) return FurLib.PERMISSION_OWNER;
if (furballs.isAdmin(addr)) return FurLib.PERMISSION_ADMIN;
if (furballs.isModerator(addr)) return FurLib.PERMISSION_MODERATOR;
return FurLib.PERMISSION_USER;
}
}
文件 16 的 35:Furballs.sol
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./editions/IFurballEdition.sol";
import "./engines/ILootEngine.sol";
import "./engines/EngineA.sol";
import "./utils/FurLib.sol";
import "./utils/FurDefs.sol";
import "./utils/FurProxy.sol";
import "./utils/Moderated.sol";
import "./utils/Governance.sol";
import "./Fur.sol";
import "./Furgreement.sol";
contract Furballs is ERC721Enumerable, Moderated {
Fur public fur;
IFurballEdition[] public editions;
ILootEngine public engine;
Governance public governance;
Furgreement public furgreement;
mapping(uint256 => FurLib.Furball) public furballs;
mapping(uint256 => FurLib.Rewards) public collect;
uint256 public intervalDuration;
event Collection(uint256 tokenId, uint256 responseId);
event Inventory(uint256 tokenId, uint128 lootId, uint16 dropped);
constructor(uint256 interval) ERC721("Furballs", "FBL") {
intervalDuration = interval;
}
function mint(address[] memory to, uint8 editionIndex, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
require(to.length == 1 || permissions >= FurLib.PERMISSION_MODERATOR, "MULT");
for (uint8 i=0; i<to.length; i++) {
fur.purchaseMint(sender, permissions, to[i], editions[editionIndex]);
_spawn(to[i], editionIndex, 0);
}
}
function feed(FurLib.Feeding[] memory feedings, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
uint256 len = feedings.length;
for (uint256 i=0; i<len; i++) {
fur.purchaseSnack(sender, permissions, feedings[i].tokenId, feedings[i].snackId, feedings[i].count);
}
}
function playMany(uint256[] memory tokenIds, uint32 zone, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
for (uint256 i=0; i<tokenIds.length; i++) {
_collect(tokenIds[i], sender, permissions);
furballs[tokenIds[i]].zone = uint32(engine.enterZone(tokenIds[i], zone, tokenIds));
}
}
function upgrade(
uint256 tokenId, uint128 lootId, uint8 chances, address actor
) external {
(address sender, uint8 permissions) = _approvedSender(actor);
uint128 up = fur.purchaseUpgrade(_baseModifiers(tokenId), sender, permissions, tokenId, lootId, chances);
if (up != 0) {
_drop(tokenId, lootId, 1);
_pickup(tokenId, up);
}
}
function pickup(uint256 tokenId, uint128 lootId) external gameAdmin {
_pickup(tokenId, lootId);
}
function drop(uint256 tokenId, uint128 lootId, uint8 count) external gameAdmin {
_drop(tokenId, lootId, count);
}
function _slotNum(uint256 tokenId, uint128 lootId) internal view returns(uint256) {
for (uint8 i=0; i<furballs[tokenId].inventory.length; i++) {
if (furballs[tokenId].inventory[i] / 256 == lootId) {
return i + 1;
}
}
return 0;
}
function _drop(uint256 tokenId, uint128 lootId, uint8 count) internal {
uint256 slot = _slotNum(tokenId, lootId);
require(slot > 0 && slot <= uint32(furballs[tokenId].inventory.length), "SLOT");
slot -= 1;
uint8 stackSize = uint8(furballs[tokenId].inventory[slot] % 0x100);
if (count == 0 || count >= stackSize) {
uint16 len = uint16(furballs[tokenId].inventory.length);
if (len > 1) {
furballs[tokenId].inventory[slot] = furballs[tokenId].inventory[len - 1];
}
furballs[tokenId].inventory.pop();
count = stackSize;
} else {
stackSize -= count;
furballs[tokenId].inventory[slot] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight -= count * engine.weightOf(lootId);
emit Inventory(tokenId, lootId, count);
}
function _pickup(uint256 tokenId, uint128 lootId) internal {
require(lootId > 0, "LOOT");
uint256 slotNum = _slotNum(tokenId, lootId);
uint8 stackSize = 1;
if (slotNum == 0) {
furballs[tokenId].inventory.push(uint256(lootId) * 0x100 + stackSize);
} else {
stackSize += uint8(furballs[tokenId].inventory[slotNum - 1] % 0x100);
require(stackSize < 0x100, "STACK");
furballs[tokenId].inventory[slotNum - 1] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight += engine.weightOf(lootId);
emit Inventory(tokenId, lootId, 0);
}
function _rewardModifiers(
FurLib.Furball memory fb, uint256 tokenId, address ownerContext, uint256 snackData
) internal view returns(FurLib.RewardModifiers memory reward) {
uint16 energy = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_ENERGY, 2));
uint16 happiness = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_HAPPINESS, 2));
bool context = ownerContext != address(0);
uint32 editionIndex = uint32(tokenId % 0x100);
reward = FurLib.RewardModifiers(
uint16(100 + fb.rarity),
uint16(100 + fb.rarity - (editionIndex < 4 ? (editionIndex * 20) : 80)),
uint16(100),
happiness,
energy,
context ? fb.zone : 0
);
return engine.modifyReward(
fb,
editions[editionIndex].modifyReward(reward, tokenId),
governance.getAccount(ownerContext),
context
);
}
function _baseModifiers(uint256 tokenId) internal view returns(FurLib.RewardModifiers memory) {
return _rewardModifiers(furballs[tokenId], tokenId, address(0), 0);
}
function _collect(uint256 tokenId, address sender, uint8 permissions) internal {
FurLib.Furball memory furball = furballs[tokenId];
address owner = ownerOf(tokenId);
require(owner == sender || permissions >= FurLib.PERMISSION_ADMIN, "OWN");
if (furball.last == 0) {
uint64 launchedAt = uint64(editions[tokenId % 0x100].liveAt());
require(launchedAt > 0 && launchedAt < uint64(block.timestamp), "PRE");
furball.last = furball.birth > launchedAt ? furball.birth : launchedAt;
}
FurLib.RewardModifiers memory mods =
_rewardModifiers(furball, tokenId, owner, fur.cleanSnacks(tokenId));
uint32 duration = uint32(uint64(block.timestamp) - furball.last);
collect[tokenId].fur = 0;
collect[tokenId].experience = 0;
collect[tokenId].levels = 0;
if (mods.zone >= 0x10000) {
uint32 f = uint32(_calculateReward(duration, FurLib.FUR_PER_INTERVAL, mods.furPercent));
if (f > 0) {
fur.earn(owner, f);
collect[tokenId].fur = f;
}
} else {
uint32 exp = uint32(_calculateReward(duration, FurLib.EXP_PER_INTERVAL, mods.expPercent));
(uint32 totalExp, uint16 levels) = engine.onExperience(furballs[tokenId], owner, exp);
collect[tokenId].experience = exp;
collect[tokenId].levels = levels;
furballs[tokenId].level += levels;
furballs[tokenId].experience = totalExp;
}
uint32 interval = uint32(intervalDuration);
uint128 lootId = engine.dropLoot(duration / interval, mods);
collect[tokenId].loot = lootId;
if (lootId > 0) {
_pickup(tokenId, lootId);
}
furballs[tokenId].last = uint64(block.timestamp);
uint32 moves = furball.moves + 1;
furballs[tokenId].moves = moves;
emit Collection(tokenId, moves);
}
function _spawn(address to, uint8 editionIndex, uint8 nonce) internal {
require(nonce < 10, "SUPPLY");
require(editionIndex < editions.length, "ED");
IFurballEdition edition = editions[editionIndex];
(uint256 tokenId, uint16 rarity) = edition.spawn();
tokenId += editionIndex;
if (_exists(tokenId)) return _spawn(to, editionIndex, nonce + 1);
uint32 owned = edition.minted(to);
require(owned < edition.maxMintable(to), "LIMIT");
uint16 cnt = edition.count();
require(cnt < edition.maxCount(), "MAX");
furballs[tokenId].number = uint32(totalSupply() + 1);
furballs[tokenId].count = cnt;
furballs[tokenId].rarity = rarity;
furballs[tokenId].birth = uint64(block.timestamp);
_mint(to, tokenId);
edition.addCount(to, 1);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
furballs[tokenId].trade = uint64(block.timestamp);
engine.onTrade(furballs[tokenId], from, to);
}
function stats(uint256 tokenId, bool contextual) public view returns(FurLib.FurballStats memory) {
FurLib.Furball memory furball = furballs[tokenId];
FurLib.RewardModifiers memory mods =
_rewardModifiers(
furball,
tokenId,
contextual ? ownerOf(tokenId) : address(0),
contextual ? fur.snackEffects(tokenId) : 0
);
return FurLib.FurballStats(
uint16(_calculateReward(intervalDuration, FurLib.EXP_PER_INTERVAL, mods.expPercent)),
uint16(_calculateReward(intervalDuration, FurLib.FUR_PER_INTERVAL, mods.furPercent)),
mods,
furball,
fur.snacks(tokenId)
);
}
function _calculateReward(
uint256 duration, uint256 perInterval, uint256 percentBoost
) internal view returns(uint256) {
uint256 interval = intervalDuration;
return (duration * percentBoost * perInterval) / (100 * interval);
}
function contractURI() public view returns (string memory) {
return governance.metaURI();
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId));
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
editions[tokenId % 0x100].tokenMetadata(
engine.attributesMetadata(tokenId),
tokenId,
furballs[tokenId].number
)
))));
}
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
return engine.canProxyTrades(owner, operator) || super.isApprovedForAll(owner, operator);
}
function _msgSender()
internal
override
view
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
function setFur(address furAddress) external onlyAdmin {
fur = Fur(furAddress);
}
function setFurgreement(address furgAddress) external onlyAdmin {
furgreement = Furgreement(furgAddress);
}
function setGovernance(address addr) public onlyAdmin {
governance = Governance(payable(addr));
}
function setEngine(address addr) public onlyAdmin {
engine = ILootEngine(addr);
}
function addEdition(address addr, uint8 idx) public onlyAdmin {
if (idx >= editions.length) {
editions.push(IFurballEdition(addr));
} else {
editions[idx] = IFurballEdition(addr);
}
}
function _isReady() internal view returns(bool) {
return address(engine) != address(0) && editions.length > 0
&& address(fur) != address(0) && address(governance) != address(0);
}
function _approvedSender(address sender) internal view returns (address, uint8) {
require(_isReady(), "!RDY");
if (sender != address(0) && sender != msg.sender) {
require(msg.sender == address(furgreement), "PROXY");
} else {
sender = _msgSender();
}
uint8 permissions = uint8(engine.approveSender(sender));
require(permissions > 0, "PLR");
return (sender, permissions);
}
modifier gameAdmin() {
(address sender, uint8 permissions) = _approvedSender(address(0));
require(permissions >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
}
文件 17 的 35:Furgreement.sol
pragma solidity ^0.8.6;
import "./Furballs.sol";
import "./utils/FurProxy.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
contract Furgreement is EIP712, FurProxy {
mapping(address => uint256) private nonces;
address[] public addressQueue;
mapping(address => PlayMove) public pendingMoves;
struct PlayMove {
uint32 zone;
uint256[] tokenIds;
}
constructor(address furballsAddress) EIP712("Furgreement", "1") FurProxy(furballsAddress) { }
function playFromSignature(
bytes memory signature,
address owner,
PlayMove memory move,
uint256 deadline
) external {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("playMany(address owner,PlayMove memory move,uint256 nonce,uint256 deadline)"),
owner,
move,
nonces[owner],
deadline
)));
address signer = ECDSA.recover(digest, signature);
require(signer == owner, "playMany: invalid signature");
require(signer != address(0), "ECDSA: invalid signature");
require(block.timestamp < deadline, "playMany: signed transaction expired");
nonces[owner]++;
if (pendingMoves[owner].tokenIds.length == 0) {
addressQueue.push(owner);
}
pendingMoves[owner] = move;
}
}
文件 18 的 35:Governance.sol
pragma solidity ^0.8.6;
import "./Stakeholders.sol";
import "./Community.sol";
import "./FurLib.sol";
contract Governance is Stakeholders {
address payable public treasury;
uint16 public transactionFee = 250;
string public metaName = "Furballs.com (Official)";
string public metaDescription =
"Furballs are entirely on-chain, with a full interactive gameplay experience at Furballs.com. "
"There are 88 billion+ possible furball combinations in the first edition, each with their own special abilities"
"... but only thousands minted per edition. Each edition has new artwork, game modes, and surprises.";
mapping(address => FurLib.Account) private _account;
address[] public accounts;
Community public community;
constructor(address furballsAddress) Stakeholders(furballsAddress) {
treasury = payable(this);
}
function metaURI() public view returns(string memory) {
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
'{"name": "', metaName,'", "description": "', metaDescription,'"',
', "external_link": "https://furballs.com"',
', "image": "https://furballs.com/images/pfp.png"',
', "seller_fee_basis_points": ', FurLib.uint2str(transactionFee),
', "fee_recipient": "0x', FurLib.bytesHex(abi.encodePacked(treasury)), '"}'
))));
}
function numAccounts() external view returns(uint256) {
return accounts.length;
}
function setMeta(string memory nameVal, string memory descVal) external gameAdmin {
metaName = nameVal;
metaDescription = descVal;
}
function setTransactionFee(uint16 basisPoints) external gameAdmin {
transactionFee = basisPoints;
}
function setTreasury(address treasuryAddress) external onlyOwner {
treasury = payable(treasuryAddress);
}
function setCommunity(address communityAddress) external onlyOwner {
community = Community(communityAddress);
}
function getAccount(address addr) external view returns (FurLib.Account memory) {
FurLib.Account memory acc = _account[addr];
acc.permissions = _userPermissions(addr);
return acc;
}
function updateStandings(address[] memory addrs) public {
for (uint32 i=0; i<addrs.length; i++) {
_updateStanding(addrs[i]);
}
}
function setReputation(address addr, uint16 rep) external gameModerators {
_account[addr].reputation = rep;
}
function updateMaxLevel(address addr, uint16 level) external gameAdmin {
if (_account[addr].maxLevel >= level) return;
_account[addr].maxLevel = level;
_updateStanding(addr);
}
function updateAccount(address addr, uint256 numFurballs) external gameAdmin {
FurLib.Account memory acc = _account[addr];
uint8 permissions = _userPermissions(addr);
if (permissions != acc.permissions) _account[addr].permissions = permissions;
if (acc.created == 0) _account[addr].created = uint64(block.timestamp);
if (acc.numFurballs != numFurballs) _account[addr].numFurballs = uint32(numFurballs);
if (numFurballs > acc.maxFurballs) {
if (acc.maxFurballs == 0) accounts.push(addr);
_account[addr].maxFurballs = uint32(numFurballs);
}
_updateStanding(addr);
}
function _updateStanding(address addr) internal {
uint256 standing = 0;
FurLib.Account memory acc = _account[addr];
if (address(community) != address(0)) {
standing = community.update(acc, addr);
} else {
uint32 num = acc.numFurballs;
if (num > 0) {
standing = num * 10 + acc.maxLevel + acc.reputation;
}
}
_account[addr].standing = uint16(standing);
}
}
文件 19 的 35:IERC165.sol
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
文件 20 的 35:IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
文件 21 的 35:IERC20Metadata.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
文件 22 的 35:IERC721.sol
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
文件 23 的 35:IERC721Enumerable.sol
pragma solidity ^0.8.0;
import "../IERC721.sol";
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
文件 24 的 35:IERC721Metadata.sol
pragma solidity ^0.8.0;
import "../IERC721.sol";
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
文件 25 的 35:IERC721Receiver.sol
pragma solidity ^0.8.0;
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
文件 26 的 35:IFurballEdition.sol
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IFurballEdition is IERC165 {
function index() external view returns(uint8);
function count() external view returns(uint16);
function maxCount() external view returns (uint16);
function addCount(address to, uint16 amount) external returns(bool);
function liveAt() external view returns(uint64);
function minted(address addr) external view returns(uint16);
function maxMintable(address addr) external view returns(uint16);
function maxAdoptable() external view returns (uint16);
function purchaseFur() external view returns(uint256);
function spawn() external returns (uint256, uint16);
function modifyReward(
FurLib.RewardModifiers memory modifiers, uint256 tokenId
) external view returns(FurLib.RewardModifiers memory);
function tokenMetadata(
bytes memory attributes, uint256 tokenId, uint256 number
) external view returns(bytes memory);
}
文件 27 的 35:ILootEngine.sol
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../editions/IFurballEdition.sol";
import "../utils/FurLib.sol";
interface ILootEngine is IERC165 {
function dropLoot(uint32 intervals, FurLib.RewardModifiers memory mods) external returns(uint128);
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external returns(uint128);
function enterZone(uint256 tokenId, uint32 zone, uint256[] memory team) external returns(uint256);
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory baseModifiers,
FurLib.Account memory account,
bool contextual
) external view returns(FurLib.RewardModifiers memory);
function weightOf(uint128 lootId) external pure returns (uint16);
function attributesMetadata(uint256 tokenId) external view returns(bytes memory);
function getSnack(uint32 snack) external view returns(FurLib.Snack memory);
function canProxyTrades(address owner, address operator) external view returns(bool);
function approveSender(address sender) external view returns(uint);
function onTrade(
FurLib.Furball memory furball, address from, address to
) external;
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external returns(uint32 totalExp, uint16 level);
function render(uint256 tokenId) external view returns(string memory);
function furballDescription(uint256 tokenId) external view returns (string memory);
}
文件 28 的 35:LootEngine.sol
pragma solidity ^0.8.6;
import "./ILootEngine.sol";
import "../editions/IFurballEdition.sol";
import "../Furballs.sol";
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
import "../utils/ProxyRegistry.sol";
import "../utils/Dice.sol";
import "../utils/Governance.sol";
import "../utils/MetaData.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
abstract contract LootEngine is ERC165, ILootEngine, Dice, FurProxy {
ProxyRegistry private _proxies;
address public companyWalletProxy;
mapping(uint32 => FurLib.Snack) private _snacks;
uint32 maxExperience = 2010000;
constructor(
address furballsAddress, address tradeProxy, address companyProxy
) FurProxy(furballsAddress) {
_proxies = ProxyRegistry(tradeProxy);
companyWalletProxy = companyProxy;
_defineSnack(0x100, 24 , 250, 15, 0);
_defineSnack(0x200, 24 * 3, 750, 20, 0);
_defineSnack(0x300, 24 * 7, 1500, 25, 0);
}
function setSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) external gameAdmin {
_defineSnack(snackId, duration, furCost, hap, en);
}
function weightOf(uint128 lootId) external virtual override pure returns (uint16) {
return 2;
}
function furballDescription(uint256 tokenId) external virtual override view returns (string memory) {
return "";
}
function render(uint256 tokenId) external virtual override view returns(string memory) {
return "";
}
function enterZone(
uint256 tokenId, uint32 zone, uint256[] memory team
) external virtual override returns(uint256) {
return uint256(zone);
}
function canProxyTrades(
address owner, address operator
) external virtual override view onlyFurballs returns(bool) {
if (address(_proxies) == address(0)) return false;
return address(_proxies.proxies(owner)) == operator;
}
function approveSender(address sender) external virtual override view onlyFurballs returns(uint) {
if (sender == companyWalletProxy && sender != address(0)) return FurLib.PERMISSION_OWNER;
return _permissions(sender);
}
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external virtual override onlyFurballs returns(uint32 totalExp, uint16 levels) {
if (experience == 0) return (0, 0);
uint32 has = furball.experience;
uint32 max = maxExperience;
totalExp = (experience < max && has < (max - experience)) ? (has + experience) : max;
uint16 oldLevel = furball.level;
uint16 level = uint16(FurLib.expToLevel(totalExp, max));
levels = level > oldLevel ? (level - oldLevel) : 0;
if (levels > 0) {
furballs.governance().updateMaxLevel(owner, level);
}
return (totalExp, levels);
}
function onTrade(
FurLib.Furball memory furball, address from, address to
) external virtual override onlyFurballs {
Governance gov = furballs.governance();
if (from != address(0)) gov.updateAccount(from, furballs.balanceOf(from) - 1);
if (to != address(0)) gov.updateAccount(to, furballs.balanceOf(to) + 1);
}
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external virtual override returns(uint128) {
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
require(rarity > 0 && rarity < 3, "RARITY");
uint32 chance = (rarity == 1 ? 75 : 25) * uint32(chances) + uint32(modifiers.luckPercent * 10);
chance = chance > 1050 ? (chance - 1000) : 50;
if (chance > 750) chance = 750;
uint32 threshold = (FurLib.Max32 / 1000) * (1000 - chance);
uint256 rolled = (uint256(roll(modifiers.expPercent)));
return rolled < threshold ? 0 : _packLoot(rarity + 1, stat);
}
function dropLoot(
uint32 intervals,
FurLib.RewardModifiers memory modifiers
) external virtual override onlyFurballs returns(uint128) {
if (modifiers.zone >= 0x10000) return 0;
(uint8 rarity, uint8 stat) = rollRarityStat(
uint32((intervals * uint256(modifiers.luckPercent)) /100), 0);
return _packLoot(rarity, stat);
}
function _packLoot(uint16 rarity, uint16 stat) internal pure returns(uint128) {
return rarity == 0 ? 0 : (uint16(rarity) * 0x10000) + (stat * 0x100);
}
function rollRarityStat(uint32 chance, uint32 seed) public returns(uint8, uint8) {
if (chance == 0) return (0, 0);
uint32 threshold = 4320;
uint32 rolled = roll(seed) % threshold;
uint8 stat = uint8(rolled % 2);
if (chance > threshold || rolled >= (threshold - chance)) return (3, stat);
threshold -= chance;
if (chance * 3 > threshold || rolled >= (threshold - chance * 3)) return (2, stat);
threshold -= chance * 3;
if (chance * 6 > threshold || rolled >= (threshold - chance * 6)) return (1, stat);
return (0, stat);
}
function getSnack(uint32 snackId) external view virtual override returns(FurLib.Snack memory) {
return _snacks[snackId];
}
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory modifiers,
FurLib.Account memory account,
bool contextual
) external virtual override view returns(FurLib.RewardModifiers memory) {
uint16 energy = modifiers.energyPoints;
uint16 weight = furball.weight;
uint16 expPercent = modifiers.expPercent + modifiers.happinessPoints;
uint16 luckPercent = modifiers.luckPercent + modifiers.happinessPoints;
uint16 furPercent = modifiers.furPercent + _furBoost(furball.level) + energy;
for (uint256 i=0; i<furball.inventory.length; i++) {
uint128 lootId = uint128(furball.inventory[i] / 0x100);
uint32 stackSize = uint32(furball.inventory[i] % 0x100);
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize);
if (stat == 0) {
expPercent += boost;
} else {
furPercent += boost;
}
}
uint256 teamSize = account.permissions < 2 ? account.numFurballs : 0;
if (teamSize < 10 && teamSize > 1) {
uint16 amt = uint16(2 * (teamSize - 1));
expPercent += amt;
furPercent += amt;
}
if (teamSize > 10) {
uint16 amt = uint16(5 * (teamSize > 20 ? 10 : (teamSize - 10)));
expPercent -= amt;
furPercent -= amt;
}
if (weight > 0) {
if (energy > 0) {
weight = (energy >= weight) ? 0 : (weight - energy);
}
if (weight > 0) {
luckPercent = weight >= luckPercent ? 0 : (luckPercent - weight);
}
}
modifiers.expPercent = expPercent;
modifiers.furPercent = furPercent;
modifiers.luckPercent = luckPercent;
return modifiers;
}
function attributesMetadata(
uint256 tokenId
) external virtual override view returns(bytes memory) {
FurLib.FurballStats memory stats = furballs.stats(tokenId, false);
return abi.encodePacked(
MetaData.traitValue("Level", stats.definition.level),
MetaData.traitValue("Rare Genes Boost", stats.definition.rarity),
MetaData.traitNumber("Edition", (tokenId % 0x100) + 1),
MetaData.traitNumber("Unique Loot Collected", stats.definition.inventory.length),
MetaData.traitBoost("EXP Boost", stats.modifiers.expPercent),
MetaData.traitBoost("FUR Boost", stats.modifiers.furPercent),
MetaData.traitDate("Acquired", stats.definition.trade),
MetaData.traitDate("Birthday", stats.definition.birth)
);
}
function _defineSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) internal {
_snacks[snackId].snackId = snackId;
_snacks[snackId].duration = duration;
_snacks[snackId].furCost = furCost;
_snacks[snackId].happiness = hap;
_snacks[snackId].energy = en;
_snacks[snackId].count = 1;
_snacks[snackId].fed = 0;
}
function _lootRarityBoost(uint16 rarity) internal pure returns (uint16) {
if (rarity == 1) return 5;
else if (rarity == 2) return 15;
else if (rarity == 3) return 30;
return 0;
}
function _furBoost(uint16 level) internal pure returns (uint16) {
if (level >= 200) return 581;
if (level < 25) return (2 * level);
if (level < 50) return (5000 + (level - 25) * 225) / 100;
if (level < 75) return (10625 + (level - 50) * 250) / 100;
if (level < 100) return (16875 + (level - 75) * 275) / 100;
if (level < 125) return (23750 + (level - 100) * 300) / 100;
if (level < 150) return (31250 + (level - 125) * 325) / 100;
if (level < 175) return (39375 + (level - 150) * 350) / 100;
return (48125 + (level - 175) * 375) / 100;
}
function _itemRarityStat(uint128 lootId) internal pure returns (uint8, uint8) {
return (
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_RARITY, 1)),
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_STAT, 1)));
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(ILootEngine).interfaceId ||
super.supportsInterface(interfaceId);
}
}
文件 29 的 35:MetaData.sol
pragma solidity ^0.8.6;
import "./FurLib.sol";
library MetaData {
function trait(string memory traitType, string memory value) internal pure returns (bytes memory) {
return abi.encodePacked('{"trait_type": "', traitType,'", "value": "', value, '"}, ');
}
function traitNumberDisplay(
string memory traitType, string memory displayType, uint256 value
) internal pure returns (bytes memory) {
return abi.encodePacked(
'{"trait_type": "', traitType,
bytes(displayType).length > 0 ? '", "display_type": "' : '', displayType,
'", "value": ', FurLib.uint2str(value), '}, '
);
}
function traitValue(string memory traitType, uint256 value) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "", value);
}
function traitBoost(
string memory traitType, uint256 percent
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "boost_percentage", percent > 100 ? (percent - 100) : 0);
}
function traitNumber(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "number", value);
}
function traitDate(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "date", value);
}
}
文件 30 的 35:Moderated.sol
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract Moderated is Ownable {
mapping (address => bool) public admins;
mapping (address => bool) public moderators;
function setAdmin(address addr, bool set) external onlyOwner {
require(addr != address(0));
admins[addr] = set;
}
function renounceOwnership() public override onlyOwner {
require(false, 'OWN');
}
function setModerator(address mod, bool set) external onlyAdmin {
require(mod != address(0));
moderators[mod] = set;
}
function isAdmin(address addr) public virtual view returns(bool) {
return owner() == addr || admins[addr];
}
function isModerator(address addr) public virtual view returns(bool) {
return isAdmin(addr) || moderators[addr];
}
modifier onlyModerators() {
require(isModerator(msg.sender), 'MOD');
_;
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), 'ADMIN');
_;
}
}
文件 31 的 35:Ownable.sol
pragma solidity ^0.8.0;
import "../utils/Context.sol";
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
文件 32 的 35:ProxyRegistry.sol
pragma solidity ^0.8.6;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
文件 33 的 35:Stakeholders.sol
pragma solidity ^0.8.6;
import "./FurProxy.sol";
import "./FurLib.sol";
import "../Furballs.sol";
abstract contract Stakeholders is FurProxy {
mapping(address => uint64) public stakes;
address[] public stakeholders;
address payable public poolAddress;
constructor(address furballsAddress) FurProxy(furballsAddress) {
poolAddress = payable(msg.sender);
}
function setPool(address addr) public onlyOwner {
poolAddress = payable(addr);
}
function setStakeholder(address addr, uint64 stake) public onlyOwner {
if (!_hasStakeholder(addr)) {
stakeholders.push(addr);
}
uint64 percent = stake;
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] != addr) {
percent += stakes[stakeholders[i]];
}
}
require(percent <= FurLib.OneHundredPercent, "Invalid stake (exceeds 100%)");
stakes[addr] = stake;
}
function withdraw() external gameAdmin {
uint256 balance = address(this).balance;
require(balance >= FurLib.OneHundredPercent, "Insufficient balance");
for (uint256 i=0; i<stakeholders.length; i++) {
address addr = stakeholders[i];
uint256 payout = balance * uint256(stakes[addr]) / FurLib.OneHundredPercent;
if (payout > 0) {
payable(addr).transfer(payout);
}
}
uint256 remaining = address(this).balance;
poolAddress.transfer(remaining);
}
function _hasStakeholder(address addr) internal view returns(bool) {
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] == addr) {
return true;
}
}
return false;
}
receive() external payable { }
}
文件 34 的 35:Strings.sol
pragma solidity ^0.8.0;
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
文件 35 的 35:draft-EIP712.sol
pragma solidity ^0.8.0;
import "./ECDSA.sol";
abstract contract EIP712 {
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
{
"compilationTarget": {
"contracts/Furballs.sol": "Furballs"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"uint256","name":"interval","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"responseId","type":"uint256"}],"name":"Collection","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"lootId","type":"uint128"},{"indexed":false,"internalType":"uint16","name":"dropped","type":"uint16"}],"name":"Inventory","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint8","name":"idx","type":"uint8"}],"name":"addEdition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"admins","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"collect","outputs":[{"internalType":"uint16","name":"levels","type":"uint16"},{"internalType":"uint32","name":"experience","type":"uint32"},{"internalType":"uint32","name":"fur","type":"uint32"},{"internalType":"uint128","name":"loot","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"lootId","type":"uint128"},{"internalType":"uint8","name":"count","type":"uint8"}],"name":"drop","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"editions","outputs":[{"internalType":"contract IFurballEdition","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"engine","outputs":[{"internalType":"contract ILootEngine","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint32","name":"snackId","type":"uint32"},{"internalType":"uint16","name":"count","type":"uint16"}],"internalType":"struct FurLib.Feeding[]","name":"feedings","type":"tuple[]"},{"internalType":"address","name":"actor","type":"address"}],"name":"feed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fur","outputs":[{"internalType":"contract Fur","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"furballs","outputs":[{"internalType":"uint32","name":"number","type":"uint32"},{"internalType":"uint16","name":"count","type":"uint16"},{"internalType":"uint16","name":"rarity","type":"uint16"},{"internalType":"uint32","name":"experience","type":"uint32"},{"internalType":"uint32","name":"zone","type":"uint32"},{"internalType":"uint16","name":"level","type":"uint16"},{"internalType":"uint16","name":"weight","type":"uint16"},{"internalType":"uint64","name":"birth","type":"uint64"},{"internalType":"uint64","name":"trade","type":"uint64"},{"internalType":"uint64","name":"last","type":"uint64"},{"internalType":"uint32","name":"moves","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"furgreement","outputs":[{"internalType":"contract Furgreement","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"governance","outputs":[{"internalType":"contract Governance","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"intervalDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"isAdmin","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"isModerator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"to","type":"address[]"},{"internalType":"uint8","name":"editionIndex","type":"uint8"},{"internalType":"address","name":"actor","type":"address"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"moderators","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"lootId","type":"uint128"}],"name":"pickup","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"uint32","name":"zone","type":"uint32"},{"internalType":"address","name":"actor","type":"address"}],"name":"playMany","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"bool","name":"set","type":"bool"}],"name":"setAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"setEngine","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"furAddress","type":"address"}],"name":"setFur","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"furgAddress","type":"address"}],"name":"setFurgreement","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"setGovernance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"mod","type":"address"},{"internalType":"bool","name":"set","type":"bool"}],"name":"setModerator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bool","name":"contextual","type":"bool"}],"name":"stats","outputs":[{"components":[{"internalType":"uint16","name":"expRate","type":"uint16"},{"internalType":"uint16","name":"furRate","type":"uint16"},{"components":[{"internalType":"uint16","name":"expPercent","type":"uint16"},{"internalType":"uint16","name":"furPercent","type":"uint16"},{"internalType":"uint16","name":"luckPercent","type":"uint16"},{"internalType":"uint16","name":"happinessPoints","type":"uint16"},{"internalType":"uint16","name":"energyPoints","type":"uint16"},{"internalType":"uint32","name":"zone","type":"uint32"}],"internalType":"struct FurLib.RewardModifiers","name":"modifiers","type":"tuple"},{"components":[{"internalType":"uint32","name":"number","type":"uint32"},{"internalType":"uint16","name":"count","type":"uint16"},{"internalType":"uint16","name":"rarity","type":"uint16"},{"internalType":"uint32","name":"experience","type":"uint32"},{"internalType":"uint32","name":"zone","type":"uint32"},{"internalType":"uint16","name":"level","type":"uint16"},{"internalType":"uint16","name":"weight","type":"uint16"},{"internalType":"uint64","name":"birth","type":"uint64"},{"internalType":"uint64","name":"trade","type":"uint64"},{"internalType":"uint64","name":"last","type":"uint64"},{"internalType":"uint32","name":"moves","type":"uint32"},{"internalType":"uint256[]","name":"inventory","type":"uint256[]"}],"internalType":"struct FurLib.Furball","name":"definition","type":"tuple"},{"components":[{"internalType":"uint32","name":"snackId","type":"uint32"},{"internalType":"uint32","name":"duration","type":"uint32"},{"internalType":"uint16","name":"furCost","type":"uint16"},{"internalType":"uint16","name":"happiness","type":"uint16"},{"internalType":"uint16","name":"energy","type":"uint16"},{"internalType":"uint16","name":"count","type":"uint16"},{"internalType":"uint64","name":"fed","type":"uint64"}],"internalType":"struct FurLib.Snack[]","name":"snacks","type":"tuple[]"}],"internalType":"struct FurLib.FurballStats","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenOfOwnerByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"lootId","type":"uint128"},{"internalType":"uint8","name":"chances","type":"uint8"},{"internalType":"address","name":"actor","type":"address"}],"name":"upgrade","outputs":[],"stateMutability":"nonpayable","type":"function"}]