// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in// construction, since the code is only stored at the end of the// constructor execution.uint256 size;
assembly {
size :=extcodesize(account)
}
return size >0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function_verifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) privatepurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 2 of 12: Context.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 3 of 12: Counters.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/libraryCounters{
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{
unchecked {
counter._value +=1;
}
}
functiondecrement(Counter storage counter) internal{
uint256 value = counter._value;
require(value >0, "Counter: decrement overflow");
unchecked {
counter._value = value -1;
}
}
functionreset(Counter storage counter) internal{
counter._value =0;
}
}
Contract Source Code
File 4 of 12: ECDSA.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @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{
/**
* @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.
*
* 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]
*/functionrecover(bytes32 hash, bytesmemory signature) internalpurereturns (address) {
// 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 recover(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 recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} 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.2._
*/functionrecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address) {
bytes32 s;
uint8 v;
assembly {
s :=and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v :=add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @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) {
// 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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.require(
uint256(s) <=0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v ==27|| v ==28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer addressaddress signer =ecrecover(hash, v, r, s);
require(signer !=address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @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 5 of 12: ERC777.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"./IERC777.sol";
import"./IERC777Recipient.sol";
import"./IERC777Sender.sol";
import"./IERC20.sol";
import"./Address.sol";
import"./Context.sol";
import"./IERC1820Registry.sol";
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/contractERC777isContext, IERC777, IERC20{
usingAddressforaddress;
IERC1820Registry internalconstant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address=>uint256) private _balances;
uint256private _totalSupply;
stringprivate _name;
stringprivate _symbol;
bytes32privateconstant _TOKENS_SENDER_INTERFACE_HASH =keccak256("ERC777TokensSender");
bytes32privateconstant _TOKENS_RECIPIENT_INTERFACE_HASH =keccak256("ERC777TokensRecipient");
// This isn't ever read from - it's only used to respond to the defaultOperators query.address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).mapping(address=>bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.mapping(address=>mapping(address=>bool)) private _operators;
mapping(address=>mapping(address=>bool)) private _revokedDefaultOperators;
// ERC20-allowancesmapping(address=>mapping(address=>uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/constructor(stringmemory name_,
stringmemory symbol_,
address[] memory defaultOperators_
) {
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i =0; i < defaultOperators_.length; i++) {
_defaultOperators[defaultOperators_[i]] =true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/functiondecimals() publicpurevirtualreturns (uint8) {
return18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/functiongranularity() publicviewvirtualoverridereturns (uint256) {
return1;
}
/**
* @dev See {IERC777-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverride(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/functionbalanceOf(address tokenHolder) publicviewvirtualoverride(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/functionsend(address recipient,
uint256 amount,
bytesmemory data
) publicvirtualoverride{
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/functiontransfer(address recipient, uint256 amount) publicvirtualoverridereturns (bool) {
require(recipient !=address(0), "ERC777: transfer to the zero address");
addressfrom= _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
returntrue;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/functionburn(uint256 amount, bytesmemory data) publicvirtualoverride{
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/functionisOperatorFor(address operator, address tokenHolder) publicviewvirtualoverridereturns (bool) {
return
operator == tokenHolder ||
(_defaultOperators[operator] &&!_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/functionauthorizeOperator(address operator) publicvirtualoverride{
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] =true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/functionrevokeOperator(address operator) publicvirtualoverride{
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] =true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/functiondefaultOperators() publicviewvirtualoverridereturns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/functionoperatorSend(address sender,
address recipient,
uint256 amount,
bytesmemory data,
bytesmemory operatorData
) publicvirtualoverride{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/functionoperatorBurn(address account,
uint256 amount,
bytesmemory data,
bytesmemory operatorData
) publicvirtualoverride{
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/functionallowance(address holder, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/functionapprove(address spender, uint256 value) publicvirtualoverridereturns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
returntrue;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/functiontransferFrom(address holder,
address recipient,
uint256 amount
) publicvirtualoverridereturns (bool) {
require(recipient !=address(0), "ERC777: transfer to the zero address");
require(holder !=address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
uint256 currentAllowance = _allowances[holder][spender];
require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance");
_approve(holder, spender, currentAllowance - amount);
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
returntrue;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/function_mint(address account,
uint256 amount,
bytesmemory userData,
bytesmemory operatorData
) internalvirtual{
_mint(account, amount, userData, operatorData, true);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If `requireReceptionAck` is set to true, and if a send hook is
* registered for `account`, the corresponding function will be called with
* `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/function_mint(address account,
uint256 amount,
bytesmemory userData,
bytesmemory operatorData,
bool requireReceptionAck
) internalvirtual{
require(account !=address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply += amount;
_balances[account] += amount;
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/function_send(addressfrom,
address to,
uint256 amount,
bytesmemory userData,
bytesmemory operatorData,
bool requireReceptionAck
) internalvirtual{
require(from!=address(0), "ERC777: send from the zero address");
require(to !=address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/function_burn(addressfrom,
uint256 amount,
bytesmemory data,
bytesmemory operatorData
) internalvirtual{
require(from!=address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variablesuint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC777: burn amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_totalSupply -= amount;
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function_move(address operator,
addressfrom,
address to,
uint256 amount,
bytesmemory userData,
bytesmemory operatorData
) private{
_beforeTokenTransfer(operator, from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC777: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/function_approve(address holder,
address spender,
uint256 value
) internal{
require(holder !=address(0), "ERC777: approve from the zero address");
require(spender !=address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/function_callTokensToSend(address operator,
addressfrom,
address to,
uint256 amount,
bytesmemory userData,
bytesmemory operatorData
) private{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer !=address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/function_callTokensReceived(address operator,
addressfrom,
address to,
uint256 amount,
bytesmemory userData,
bytesmemory operatorData,
bool requireReceptionAck
) private{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer !=address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} elseif (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(address operator,
addressfrom,
address to,
uint256 amount
) internalvirtual{}
}
Contract Source Code
File 6 of 12: IERC1820Registry.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/interfaceIERC1820Registry{
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/functionsetManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/functiongetManager(address account) externalviewreturns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/functionsetInterfaceImplementer(address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/functiongetInterfaceImplementer(address account, bytes32 _interfaceHash) externalviewreturns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/functioninterfaceHash(stringcalldata interfaceName) externalpurereturns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/functionupdateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/functionimplementsERC165Interface(address account, bytes4 interfaceId) externalviewreturns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/functionimplementsERC165InterfaceNoCache(address account, bytes4 interfaceId) externalviewreturns (bool);
eventInterfaceImplementerSet(addressindexed account, bytes32indexed interfaceHash, addressindexed implementer);
eventManagerChanged(addressindexed account, addressindexed newManager);
}
Contract Source Code
File 7 of 12: IERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/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 8 of 12: IERC777.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/interfaceIERC777{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/functiongranularity() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/functionbalanceOf(address owner) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/functionsend(address recipient,
uint256 amount,
bytescalldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/functionburn(uint256 amount, bytescalldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/functionisOperatorFor(address operator, address tokenHolder) externalviewreturns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/functionauthorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/functionrevokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/functiondefaultOperators() externalviewreturns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/functionoperatorSend(address sender,
address recipient,
uint256 amount,
bytescalldata data,
bytescalldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/functionoperatorBurn(address account,
uint256 amount,
bytescalldata data,
bytescalldata operatorData
) external;
eventSent(addressindexed operator,
addressindexedfrom,
addressindexed to,
uint256 amount,
bytes data,
bytes operatorData
);
eventMinted(addressindexed operator, addressindexed to, uint256 amount, bytes data, bytes operatorData);
eventBurned(addressindexed operator, addressindexedfrom, uint256 amount, bytes data, bytes operatorData);
eventAuthorizedOperator(addressindexed operator, addressindexed tokenHolder);
eventRevokedOperator(addressindexed operator, addressindexed tokenHolder);
}
Contract Source Code
File 9 of 12: IERC777Recipient.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/interfaceIERC777Recipient{
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/functiontokensReceived(address operator,
addressfrom,
address to,
uint256 amount,
bytescalldata userData,
bytescalldata operatorData
) external;
}
Contract Source Code
File 10 of 12: IERC777Sender.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/interfaceIERC777Sender{
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/functiontokensToSend(address operator,
addressfrom,
address to,
uint256 amount,
bytescalldata userData,
bytescalldata operatorData
) external;
}
Contract Source Code
File 11 of 12: draft-EIP712.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;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) {
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;
}
/**
* @dev Returns the domain separator for the current chain.
*/function_domainSeparatorV4() internalviewreturns (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
) privateviewreturns (bytes32) {
returnkeccak256(abi.encode(typeHash, nameHash, versionHash, block.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);
}
}
Contract Source Code
File 12 of 12: tgt.sol
// SPDX-License-Identifier: MPLpragmasolidity ~0.8.4;import"./ERC777.sol";
import"./draft-EIP712.sol";
import"./ECDSA.sol";
import"./Counters.sol";
//interface IERC20 comes from openzeppelininterfaceIERC20MetadataisIERC20{
functionname() externalviewreturns (stringmemory);
functionsymbol() externalviewreturns (stringmemory);
functiondecimals() externalviewreturns (uint8);
}
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/draft-IERC20Permit.solinterfaceIERC20Permit{
functionpermit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
functionnonces(address owner) externalviewreturns (uint256);
functionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
//the function transferFromAndCall was added so that with a permit, also a function can be calledinterfaceIERC677ish{
functiontransferAndCall(address to, uint256 value, bytescalldata data) externalreturns (bool success);
functiontransferFromAndCall(address sender, address to, uint256 value, bytescalldata data) externalreturns (bool success);
eventTransferWithData(addressindexedfrom, addressindexed to, uint256 value, bytes data);
}
interfaceIERC677Receiver{
functiononTokenTransfer(address sender, uint value, bytescalldata data) external;
}
contractTGTisIERC20Metadata, IERC20Permit, IERC677ish, EIP712{
eventMinted(addressindexed operator, addressindexed to, uint256 amount, bytes data, bytes operatorData);
eventBurned(addressindexed operator, addressindexedfrom, uint256 amount, bytes data, bytes operatorData);
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint256private _totalSupply;
uint96private _totalEmitted;
uint64private _live =0;
addressprivate _owner;
addressprivate _reserve;
uint64private _lastEmitMAt;
uint64private _lastEmitYAt;
uint8[] private _curveHalvingYears = [5,5,4,4,3,3,2,2,1]; //1 year has 360 days -> 1 month = 30 daysuint96private _curveSupply = INIT_SUPPLY;
uint96constant MAX_SUPPLY =1000000000* (10**18); //1 billionuint96constant INIT_SUPPLY =750000000* (10**18); //460 + 290(locked) millionuint64constant MAX_INT =2**64-1;
uint64constant MONTH_IN_S =60*60*24*30;
constructor() EIP712(symbol(), "1") {
_owner =msg.sender;
_reserve =msg.sender;
}
modifieronlyOwner(){
require(msg.sender== _owner, "TGT: not the owner");
_;
}
functionsetCurve(uint8[] calldata curveHalvingYears) publicvirtualonlyOwner{
require(curveHalvingYears.length>=5, 'TGT: curveHalvingYears not >= 5');
require(curveHalvingYears[curveHalvingYears.length-1] ==1, 'TGT: last value must be 1');
for(uint256 i=0;i<curveHalvingYears.length-1;i++) {
require(curveHalvingYears[i] >1, 'TGT: values must be > 1');
}
_curveHalvingYears = curveHalvingYears;
}
functiontransferOwner(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "TGT: transfer owner the zero address");
require(newOwner !=address(this), "TGT: transfer owner to this contract");
_owner = newOwner;
}
functionsetReserve(address reserve) publicvirtualonlyOwner{
require(reserve !=address(0), "TGT: set reserve to zero address");
require(reserve !=address(this), "TGT: set reserve to this contract");
_reserve = reserve;
}
functionlive() publicviewreturns (uint64) {
return _live;
}
functionname() publicviewvirtualoverridereturns (stringmemory) {
return"THORWallet Governance Token";
}
functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return"TGT";
}
functiondecimals() publicviewvirtualoverridereturns (uint8) {
return18;
}
functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
functionbalanceOf(address account) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
functiontransfer(address recipient, uint256 amount) publicvirtualoverridereturns (bool) {
require(recipient !=address(0), "ERC20: transfer to the zero address");
require(recipient !=address(this), "ERC20: transfer to this contract");
_transfer(msg.sender, recipient, amount);
returntrue;
}
functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
functionapprove(address spender, uint256 amount) publicvirtualoverridereturns (bool) {
_approve(msg.sender, spender, amount);
returntrue;
}
functiontransferFrom(address sender, address recipient, uint256 amount) publicvirtualoverridereturns (bool) {
require(recipient !=address(0), "ERC20: transfer to the zero address");
require(recipient !=address(this), "ERC20: transfer to this contract");
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
returntrue;
}
functionburn(uint256 amount) publicvirtual{
_transfer(msg.sender, address(0), amount);
_totalSupply -= amount;
}
functionmint(address[] calldata account, uint96[] calldata amount) publicvirtualonlyOwner{
require(account.length== amount.length, "TGT: accounts and amounts length must match");
require(_live ==0, "TGT: contract already live. It should be not live (live==false)");
for(uint256 i=0;i<account.length;i++) {
require(account[i] !=address(0), "ERC20: mint to the zero address");
require(account[i] !=address(this), "TGT: sender is this contract");
_totalSupply += amount[i];
_balances[account[i]] += amount[i];
emit Transfer(address(0), account[i], amount[i]);
}
require(_totalSupply <= INIT_SUPPLY, "TGT: surpassing INIT_SUPPLY");
}
functionemitTokens() publicvirtual{
require(_live !=0, "TGT: contract not live yet. It should be live (live==true)");
uint64 timeInM =uint64((block.timestamp- _live) / MONTH_IN_S);
if (timeInM <= _lastEmitMAt) {
return;
}
// timeInM at the start will be 1, so subtract 1 so that we start after one// month with the emission from 0, to emit the full amount.uint64 timeInY = (timeInM -1) /12;
if (timeInY >= _curveHalvingYears.length) {
_lastEmitMAt = MAX_INT;
//now we mint all the tokens, also if we forgot a monthly emituint96 toBeMintedFinal = (MAX_SUPPLY - INIT_SUPPLY) - _totalEmitted;
_totalSupply += toBeMintedFinal;
_balances[_reserve] += toBeMintedFinal;
if (isContract(_reserve)) {
IERC677Receiver(_reserve).onTokenTransfer(address(this), toBeMintedFinal, "");
}
emit Transfer(address(0), _reserve, toBeMintedFinal);
return;
}
if (timeInY > _lastEmitYAt) {
uint96 toBeMintedOld = MAX_SUPPLY - _curveSupply;
uint96 lastYearlyMint = toBeMintedOld / _curveHalvingYears[_lastEmitYAt];
_curveSupply += lastYearlyMint;
_lastEmitYAt = timeInY;
}
uint96 toBeMinted = MAX_SUPPLY - _curveSupply;
uint96 yearlyMint = toBeMinted / _curveHalvingYears[timeInY];
uint96 additionalAmountM = yearlyMint /12;
_totalSupply += additionalAmountM;
_totalEmitted += additionalAmountM;
_balances[_reserve] += additionalAmountM;
_lastEmitMAt = timeInM;
if (isContract(_reserve)) {
IERC677Receiver(_reserve).onTokenTransfer(address(this), additionalAmountM, "");
}
emit Transfer(address(0), _reserve, additionalAmountM);
}
functionmintFinish() publicvirtualonlyOwner{
require(_totalSupply == INIT_SUPPLY, "TGT: supply mismatch");
require(_live ==0, "TGT: contract is live already. It should be not live (live==false)");
_live =uint64(block.timestamp);
}
functionincreaseAllowance(address spender, uint256 addedValue) publicvirtualreturns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
returntrue;
}
functiondecreaseAllowance(address spender, uint256 subtractedValue) publicvirtualreturns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(msg.sender, spender, currentAllowance - subtractedValue);
}
returntrue;
}
functiontransferAndCall(address to, uint value, bytescalldata data) publicvirtualoverridereturns (bool success) {
transferFromAndCall(msg.sender, to, value, data);
returntrue;
}
functiontransferFromAndCall(address sender, address to, uint value, bytescalldata data) publicvirtualoverridereturns (bool success) {
transferFrom(sender, to, value);
emit TransferWithData(sender, to, value, data);
if (isContract(to)) {
IERC677Receiver(to).onTokenTransfer(sender, value, data);
}
returntrue;
}
functionisContract(address addr) privateviewreturns (bool hasCode) {
uint length;
assembly { length :=extcodesize(addr) }
return length >0;
}
function_transfer(address sender, address recipient, uint256 amount) internalvirtual{
//the recipient is checked by the callee, as this is also used for token burn, which//goes to address 0require(sender !=address(0), "ERC20: transfer from the zero address");
require(sender !=address(this), "TGT: sender is this contract");
require(_live !=0, "TGT: contract not live yet. It should be live (live==true)");
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);
}
function_approve(address owner, address spender, uint256 amount) internalvirtual{
require(owner !=address(0), "ERC20: approve from the zero address");
require(owner !=address(this), "TGT: owner is this contract");
require(spender !=address(0), "ERC20: approve to the zero address");
require(spender !=address(this), "TGT: spender is this contract");
require(_live !=0, "TGT: contract not live yet. It should be live (live==true)");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// ************ ERC777 ********************usingCountersforCounters.Counter;
mapping (address=> Counters.Counter) private _nonces;
bytes32privateimmutable _PERMIT_TYPEHASH =keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
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);
}
functionnonces(address owner) publicviewvirtualoverridereturns (uint256) {
return _nonces[owner].current();
}
functionDOMAIN_SEPARATOR() externalviewoverridereturns (bytes32) {
return _domainSeparatorV4();
}
function_useNonce(address owner) internalvirtualreturns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}