// SPDX-License-Identifier: AGPL-3.0-or-laterpragmasolidity ^0.7.5;import"./SafeMath.sol";
libraryCounters{
usingSafeMathforuint256;
structCounter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add// this feature: see https://github.com/ethereum/solidity/issues/4637uint256 _value; // default: 0
}
functioncurrent(Counter storage counter) internalviewreturns (uint256) {
return counter._value;
}
functionincrement(Counter storage counter) internal{
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value +=1;
}
functiondecrement(Counter storage counter) internal{
counter._value = counter._value.sub(1);
}
}
Contract Source Code
File 2 of 12: ECDSA.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.7.5;/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/libraryECDSA{
enumRecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function_throwError(RecoverError error) privatepure{
if (error == RecoverError.NoError) {
return; // no error: do nothing
} elseif (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} elseif (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} elseif (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} elseif (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, bytesmemory signature) internalpurereturns (address, RecoverError) {
// Check the signature length// - case 65: r,s,v signature (standard)// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._if (signature.length==65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly.assembly {
r :=mload(add(signature, 0x20))
s :=mload(add(signature, 0x40))
v :=byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} elseif (signature.length==64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly.assembly {
r :=mload(add(signature, 0x20))
vs :=mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/functionrecover(bytes32 hash, bytesmemory signature) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s :=and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v :=add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/functionrecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most// signatures from current libraries generate a unique signature with an s-value in the lower half order.//// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept// these malleable signatures as well.if (uint256(s) >0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v !=27&& v !=28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer addressaddress signer =ecrecover(hash, v, r, s);
if (signer ==address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/functionrecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytes32 hash) internalpurereturns (bytes32) {
// 32 is the length in bytes of hash,// enforced by the type signature abovereturnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/functiontoTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
Contract Source Code
File 3 of 12: EIP712.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.7.5;import"./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/abstractcontractEIP712{
/* solhint-disable var-name-mixedcase */// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to// invalidate the cached domain separator if the chain id changes.bytes32privateimmutable _CACHED_DOMAIN_SEPARATOR;
uint256privateimmutable _CACHED_CHAIN_ID;
bytes32privateimmutable _HASHED_NAME;
bytes32privateimmutable _HASHED_VERSION;
bytes32privateimmutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase *//**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/constructor(stringmemory name, stringmemory version) {
uint256 chainID;
assembly {
chainID :=chainid()
}
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 = chainID;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/function_domainSeparatorV4() internalviewreturns (bytes32) {
uint256 chainID;
assembly {
chainID :=chainid()
}
if (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
) privateviewreturns (bytes32) {
uint256 chainID;
assembly {
chainID :=chainid()
}
returnkeccak256(abi.encode(typeHash, nameHash, versionHash, chainID, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/function_hashTypedDataV4(bytes32 structHash) internalviewvirtualreturns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MITpragmasolidity >=0.7.5;import"../interfaces/IERC20Permit.sol";
import"./ERC20.sol";
import"../cryptography/EIP712.sol";
import"../cryptography/ECDSA.sol";
import"../libraries/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/abstractcontractERC20PermitisERC20, IERC20Permit, EIP712{
usingCountersforCounters.Counter;
mapping(address=> Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcasebytes32privateimmutable _PERMIT_TYPEHASH =keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/constructor(stringmemory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtualoverride{
require(block.timestamp<= deadline, "ERC20Permit: expired deadline");
bytes32 structHash =keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/functionnonces(address owner) publicviewvirtualoverridereturns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewoverridereturns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/function_useNonce(address owner) internalvirtualreturns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
Contract Source Code
File 6 of 12: IERC20.sol
// SPDX-License-Identifier: AGPL-3.0-or-laterpragmasolidity >=0.7.5;interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address recipient, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(address sender, address recipient, uint256 amount) externalreturns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
}
Contract Source Code
File 7 of 12: IERC20Permit.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.7.5;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as th xe allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
// SPDX-License-Identifier: AGPL-3.0-or-laterpragmasolidity ^0.7.5;// TODO(zx): Replace all instances of SafeMath with OZ implementationlibrarySafeMath{
functionadd(uint256 a, uint256 b) internalpurereturns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
functionsub(uint256 a, uint256 b) internalpurereturns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
functionsub(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
functionmul(uint256 a, uint256 b) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
functiondiv(uint256 a, uint256 b) internalpurereturns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
functiondiv(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b >0, errorMessage);
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't holdreturn c;
}
// Only used in the BondingCalculator.solfunctionsqrrt(uint256 a) internalpurereturns (uint c) {
if (a >3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} elseif (a !=0) {
c =1;
}
}
}
Contract Source Code
File 12 of 12: sFloorERC20.sol
// SPDX-License-Identifier: AGPL-3.0-or-laterpragmasolidity ^0.7.5;import"./libraries/SafeMath.sol";
import"./types/ERC20Permit.sol";
import"./interfaces/IgFLOOR.sol";
import"./interfaces/IsFLOOR.sol";
import"./interfaces/IStaking.sol";
contractsFLOORisIsFLOOR, ERC20Permit{
/* ========== DEPENDENCIES ========== */usingSafeMathforuint256;
/* ========== EVENTS ========== */eventLogSupply(uint256indexed epoch, uint256 totalSupply);
eventLogRebase(uint256indexed epoch, uint256 rebaseAmount, uint256 index);
eventLogStakingContractUpdated(address stakingContract);
/* ========== MODIFIERS ========== */modifieronlyStakingContract() {
require(msg.sender== stakingContract, "StakingContract: call is not staking contract");
_;
}
/* ========== DATA STRUCTURES ========== */structRebase {
uint256 epoch;
uint256 totalStakedBefore;
uint256 totalStakedAfter;
uint256 amountRebased;
uint256 index;
uint256 blockNumberOccured;
}
/* ========== STATE VARIABLES ========== */addressinternal initializer;
uint256internal INDEX; // Index Gons - tracks rebase growthaddresspublic stakingContract; // balance used to calc rebase
IgFLOOR public gFLOOR; // additional staked supply (governance token)
Rebase[] public rebases; // past rebase datauint256privateconstant MAX_UINT256 =type(uint256).max;
uint256privateconstant INITIAL_FRAGMENTS_SUPPLY =5_000_000*10**9;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.// Use the highest value that fits in a uint256 for max granularity.uint256privateconstant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2uint256privateconstant MAX_SUPPLY =~uint128(0); // (2^128) - 1uint256private _gonsPerFragment;
mapping(address=>uint256) private _gonBalances;
mapping(address=>mapping(address=>uint256)) private _allowedValue;
addresspublic treasury;
mapping(address=>uint256) publicoverride debtBalances;
/* ========== CONSTRUCTOR ========== */constructor() ERC20("Staked FLOOR", "sFLOOR", 9) ERC20Permit("Staked FLOOR") {
initializer =msg.sender;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
}
/* ========== INITIALIZATION ========== */functionsetIndex(uint256 _index) external{
require(msg.sender== initializer, "Initializer: caller is not initializer");
require(INDEX ==0, "Cannot set INDEX again");
INDEX = gonsForBalance(_index);
}
functionsetgFLOOR(address _gFLOOR) external{
require(msg.sender== initializer, "Initializer: caller is not initializer");
require(address(gFLOOR) ==address(0), "gFLOOR: gFLOOR already set");
require(_gFLOOR !=address(0), "gFLOOR: gFLOOR is not a valid contract");
gFLOOR = IgFLOOR(_gFLOOR);
}
// do this lastfunctioninitialize(address _stakingContract, address _treasury) external{
require(msg.sender== initializer, "Initializer: caller is not initializer");
require(_stakingContract !=address(0), "Staking");
stakingContract = _stakingContract;
_gonBalances[stakingContract] = TOTAL_GONS;
require(_treasury !=address(0), "Zero address: Treasury");
treasury = _treasury;
emit Transfer(address(0x0), stakingContract, _totalSupply);
emit LogStakingContractUpdated(stakingContract);
initializer =address(0);
}
/* ========== REBASE ========== *//**
@notice increases sFLOOR supply to increase staking balances relative to profit_
@param profit_ uint256
@return uint256
*/functionrebase(uint256 profit_, uint256 epoch_) publicoverrideonlyStakingContractreturns (uint256) {
uint256 rebaseAmount;
uint256 circulatingSupply_ = circulatingSupply();
if (profit_ ==0) {
emit LogSupply(epoch_, _totalSupply);
emit LogRebase(epoch_, 0, index());
return _totalSupply;
} elseif (circulatingSupply_ >0) {
rebaseAmount = profit_.mul(_totalSupply).div(circulatingSupply_);
} else {
rebaseAmount = profit_;
}
_totalSupply = _totalSupply.add(rebaseAmount);
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
_storeRebase(circulatingSupply_, profit_, epoch_);
return _totalSupply;
}
/**
@notice emits event with data about rebase
@param previousCirculating_ uint
@param profit_ uint
@param epoch_ uint
*/function_storeRebase(uint256 previousCirculating_,
uint256 profit_,
uint256 epoch_
) internal{
rebases.push(
Rebase({
epoch: epoch_,
totalStakedBefore: previousCirculating_,
totalStakedAfter: circulatingSupply(),
amountRebased: profit_,
index: index(),
blockNumberOccured: block.number
})
);
emit LogSupply(epoch_, _totalSupply);
emit LogRebase(epoch_, profit_, index());
}
/* ========== MUTATIVE FUNCTIONS =========== */functiontransfer(address to, uint256 value) publicoverride(IERC20, ERC20) returns (bool) {
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
require(balanceOf(msg.sender) >= debtBalances[msg.sender], "Debt: cannot transfer amount");
emit Transfer(msg.sender, to, value);
returntrue;
}
functiontransferFrom(addressfrom,
address to,
uint256 value
) publicoverride(IERC20, ERC20) returns (bool) {
_allowedValue[from][msg.sender] = _allowedValue[from][msg.sender].sub(value);
emit Approval(from, msg.sender, _allowedValue[from][msg.sender]);
uint256 gonValue = gonsForBalance(value);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
require(balanceOf(from) >= debtBalances[from], "Debt: cannot transfer amount");
emit Transfer(from, to, value);
returntrue;
}
functionapprove(address spender, uint256 value) publicoverride(IERC20, ERC20) returns (bool) {
_approve(msg.sender, spender, value);
returntrue;
}
functionincreaseAllowance(address spender, uint256 addedValue) publicoverridereturns (bool) {
_approve(msg.sender, spender, _allowedValue[msg.sender][spender].add(addedValue));
returntrue;
}
functiondecreaseAllowance(address spender, uint256 subtractedValue) publicoverridereturns (bool) {
uint256 oldValue = _allowedValue[msg.sender][spender];
if (subtractedValue >= oldValue) {
_approve(msg.sender, spender, 0);
} else {
_approve(msg.sender, spender, oldValue.sub(subtractedValue));
}
returntrue;
}
// this function is called by the treasury, and informs sFLOOR of changes to debt.// note that addresses with debt balances cannot transfer collateralized sFLOOR// until the debt has been repaid.functionchangeDebt(uint256 amount,
address debtor,
bool add
) externaloverride{
require(msg.sender== treasury, "Only treasury");
if (add) {
debtBalances[debtor] = debtBalances[debtor].add(amount);
} else {
debtBalances[debtor] = debtBalances[debtor].sub(amount);
}
require(debtBalances[debtor] <= balanceOf(debtor), "sFLOOR: insufficient balance");
}
/* ========== INTERNAL FUNCTIONS ========== */function_approve(address owner,
address spender,
uint256 value
) internalvirtualoverride{
_allowedValue[owner][spender] = value;
emit Approval(owner, spender, value);
}
/* ========== VIEW FUNCTIONS ========== */functionbalanceOf(address who) publicviewoverride(IERC20, ERC20) returns (uint256) {
return _gonBalances[who].div(_gonsPerFragment);
}
functiongonsForBalance(uint256 amount) publicviewoverridereturns (uint256) {
return amount.mul(_gonsPerFragment);
}
functionbalanceForGons(uint256 gons) publicviewoverridereturns (uint256) {
return gons.div(_gonsPerFragment);
}
// toG converts an sFLOOR balance to gFLOOR terms. gFLOOR is an 18 decimal token. balance given is in 18 decimal format.functiontoG(uint256 amount) externalviewoverridereturns (uint256) {
return gFLOOR.balanceTo(amount);
}
// fromG converts a gFLOOR balance to sFLOOR terms. sFLOOR is a 9 decimal token. balance given is in 9 decimal format.functionfromG(uint256 amount) externalviewoverridereturns (uint256) {
return gFLOOR.balanceFrom(amount);
}
// Staking contract holds excess sFLOORfunctioncirculatingSupply() publicviewoverridereturns (uint256) {
return
_totalSupply.sub(balanceOf(stakingContract)).add(gFLOOR.balanceFrom(IERC20(address(gFLOOR)).totalSupply())).add(
IStaking(stakingContract).supplyInWarmup()
);
}
functionindex() publicviewoverridereturns (uint256) {
return balanceForGons(INDEX);
}
functionallowance(address owner_, address spender) publicviewoverride(IERC20, ERC20) returns (uint256) {
return _allowedValue[owner_][spender];
}
}