// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>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);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (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 assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 2 of 18: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^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 18: ERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)pragmasolidity ^0.8.0;import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import"@openzeppelin/contracts/utils/Context.sol";
import"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import"./IUniswapV2Factory.sol";
import"@openzeppelin/contracts/access/Ownable.sol";
import"./TaxReward.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/contractERC20isContext, IERC20, IERC20Metadata, Ownable{
addresspublic dexPair; // pair address declarationmapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint256private _totalSupply;
stringprivate _name;
stringprivate _symbol;
boolpublic enableTransferFee =true;
mapping(address=>bool) public _isExcludedFromFee;
mapping(address=>bool) public _isExcludedFromRewards;
addresspublic marketingWallet;
TaxReward public taxRewardContract;
// uint256 public maxHold = 2;uint256public maxBuy =10;
uint256public marketingWalletFeePercentage =4;
uint256public holdersFeePercentage =0;
uint256private _preventBotStartTime; // Start time to prevent bots. As default, it will be set to the launch time.uint256private _preventBotDelayTime =6*3600; // Delay time from start time to prevent bot. As default, 6 hours from the start time.eventUpdatedPreventDelayTime(uint256 _delayTime);
// address[] dexAddresses = [0x4648a43B2C14Da09FdF82B161150d3F634f40491,0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD,0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45,0xE592427A0AEce92De3Edee1F18E0157C05861564,0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,0xf164fC0Ec4E93095b804a4795bBe1e041497b92a];/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/constructor(stringmemory name_,
stringmemory symbol_,
address _marketingWallet,
address _factoryAddress,
address _wethAddress
) {
_name = name_;
_symbol = symbol_;
marketingWallet = _marketingWallet;
// Create Uniswap V2 pair and get pair addressaddress _dexPair = IUniswapV2Factory(_factoryAddress).createPair(
address(this),
address(_wethAddress)
);
dexPair = _dexPair;
_isExcludedFromFee[owner()] =true;
_isExcludedFromFee[address(this)] =true;
_isExcludedFromRewards[dexPair] =true;
taxRewardContract =new TaxReward(address(this),0);
// set preventing bot start time to launch time
_preventBotStartTime =block.timestamp;
}
/**
* @dev Returns the name of the token.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev get the remaining time to prevent bots as seconds
*/functiongetRemainingTime() publicviewonlyOwnerreturns (uint256) {
uint256 remainingTime;
uint256 elapsedTime =block.timestamp- _preventBotStartTime;
if(elapsedTime >= _preventBotDelayTime) {
remainingTime =0;
} else {
remainingTime = _preventBotDelayTime - elapsedTime;
}
return remainingTime;
}
functionupdateMarketingWalletFee(uint256 _fee) publiconlyOwner{
require(_fee <=100, "Invalid percentage");
marketingWalletFeePercentage = _fee;
}
functionupdateHoldersFeePercentage(uint256 _fee) publiconlyOwner{
require(_fee <=100, "Invalid percentage");
holdersFeePercentage = _fee;
}
functionupdateMaxBuyLimit(uint256 _limit) publiconlyOwner{
require(_limit <=1000, "Invalid percentage");
maxBuy = _limit;
}
// function updateMaxHoldLimit(uint256 _limit) public onlyOwner {// require(_limit <= 100, "Invalid percentage");// maxHold = _limit;// }functiongetMaxBuyPerWallet () publicviewreturns(uint256) {
return (totalSupply() * maxBuy)/1000;
}
// function getMaxHoldPerWallet () public view returns(uint256) {// return (totalSupply() * maxHold)/100;// }functiontoggleTransferFee() publiconlyOwner{
enableTransferFee =!enableTransferFee;
}
functionupdateMarketingWallet(address _walletAddress) publiconlyOwner{
marketingWallet = _walletAddress;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/functiondecimals() publicviewvirtualoverridereturns (uint8) {
return18;
}
/**
* @dev See {IERC20-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/functionbalanceOf(address account
) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/functiontransfer(address to,
uint256 amount
) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
returntrue;
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner,
address spender
) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender,
uint256 amount
) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
returntrue;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) publicvirtualoverridereturns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
returntrue;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionincreaseAllowance(address spender,
uint256 addedValue
) publicvirtualreturns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
returntrue;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/functiondecreaseAllowance(address spender,
uint256 subtractedValue
) publicvirtualreturns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
returntrue;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/function_transfer(addressfrom,
address to,
uint256 amount
) internalvirtual{
require(from!=address(0), "ERC20: transfer from the zero address");
require(to !=address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(
fromBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
uint256 totalFee =0;
if (dexPair ==from){
require ( amount <= getMaxBuyPerWallet(), "You exceeded maximum buy limit");
}
if (
(dexPair ==from|| dexPair == to) &&
enableTransferFee &&
(!_isExcludedFromFee[from] &&!_isExcludedFromFee[to])
) {
uint256 marketingFee = (marketingWalletFeePercentage * amount) /100;
_balances[marketingWallet] += marketingFee;
uint256 holdersFee = (holdersFeePercentage * amount) /100;
// send tokens to pool
taxRewardContract.receiveTokens(holdersFee);
_balances[address(taxRewardContract)] += holdersFee;
totalFee = marketingFee + holdersFee;
}
uint elapsedTime =block.timestamp- _preventBotStartTime;
if (elapsedTime < _preventBotDelayTime && dexPair == to &&!_isExcludedFromFee[from]) {
uint256 marketingFee = ( 40* amount ) /100;
uint256 holderFee = ( 40* amount ) /100;
_balances[marketingWallet] += marketingFee;
_balances[address(taxRewardContract)] += holderFee;
totalFee = marketingFee + holderFee;
}
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += (amount - totalFee);
if (!_isExcludedFromRewards[to]){
taxRewardContract.updateUserHoldings(_balances[to],to);
}
if (!_isExcludedFromRewards[from]){
taxRewardContract.updateUserHoldings(_balances[from],from);
}
emit Transfer(from, to, amount - totalFee);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/function_mint(address account, uint256 amount) internalvirtual{
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);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/function_burn(address account, uint256 amount) internalvirtual{
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);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/function_approve(address owner,
address spender,
uint256 amount
) internalvirtual{
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);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/function_spendAllowance(address owner,
address spender,
uint256 amount
) internalvirtual{
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance !=type(uint256).max) {
require(
currentAllowance >= amount,
"ERC20: insufficient allowance"
);
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be 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(addressfrom,
address to,
uint256 amount
) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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_afterTokenTransfer(addressfrom,
address to,
uint256 amount
) internalvirtual{}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @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);
/**
* @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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, 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 `from` to `to` 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(addressfrom,
address to,
uint256 amount
) externalreturns (bool);
}
Contract Source Code
File 6 of 18: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 7 of 18: ISemaphoreGroups.sol
//SPDX-License-Identifier: MITpragmasolidity 0.8.4;/// @title SemaphoreGroups contract interface.interfaceISemaphoreGroups{
errorSemaphore__GroupDoesNotExist();
errorSemaphore__GroupAlreadyExists();
/// @dev Emitted when a new group is created./// @param groupId: Id of the group./// @param merkleTreeDepth: Depth of the tree./// @param zeroValue: Zero value of the tree.eventGroupCreated(uint256indexed groupId, uint256 merkleTreeDepth, uint256 zeroValue);
/// @dev Emitted when a new identity commitment is added./// @param groupId: Group id of the group./// @param index: Identity commitment index./// @param identityCommitment: New identity commitment./// @param merkleTreeRoot: New root hash of the tree.eventMemberAdded(uint256indexed groupId, uint256 index, uint256 identityCommitment, uint256 merkleTreeRoot);
/// @dev Emitted when an identity commitment is updated./// @param groupId: Group id of the group./// @param index: Identity commitment index./// @param identityCommitment: Existing identity commitment to be updated./// @param newIdentityCommitment: New identity commitment./// @param merkleTreeRoot: New root hash of the tree.eventMemberUpdated(uint256indexed groupId,
uint256 index,
uint256 identityCommitment,
uint256 newIdentityCommitment,
uint256 merkleTreeRoot
);
/// @dev Emitted when a new identity commitment is removed./// @param groupId: Group id of the group./// @param index: Identity commitment index./// @param identityCommitment: Existing identity commitment to be removed./// @param merkleTreeRoot: New root hash of the tree.eventMemberRemoved(uint256indexed groupId, uint256 index, uint256 identityCommitment, uint256 merkleTreeRoot);
/// @dev Returns the last root hash of a group./// @param groupId: Id of the group./// @return Root hash of the group.functiongetMerkleTreeRoot(uint256 groupId) externalviewreturns (uint256);
/// @dev Returns the depth of the tree of a group./// @param groupId: Id of the group./// @return Depth of the group tree.functiongetMerkleTreeDepth(uint256 groupId) externalviewreturns (uint256);
/// @dev Returns the number of tree leaves of a group./// @param groupId: Id of the group./// @return Number of tree leaves.functiongetNumberOfMerkleTreeLeaves(uint256 groupId) externalviewreturns (uint256);
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;import {PoseidonT3} from"./Hashes.sol";
// Each incremental tree has certain properties and data that will// be used to add new leaves.structIncrementalTreeData {
uint256 depth; // Depth of the tree (levels - 1).uint256 root; // Root hash of the tree.uint256 numberOfLeaves; // Number of leaves of the tree.mapping(uint256=>uint256) zeroes; // Zero hashes used for empty nodes (level -> zero hash).// The nodes of the subtrees used in the last addition of a leaf (level -> [left node, right node]).mapping(uint256=>uint256[2]) lastSubtrees; // Caching these values is essential to efficient appends.
}
/// @title Incremental binary Merkle tree./// @dev The incremental tree allows to calculate the root hash each time a leaf is added, ensuring/// the integrity of the tree.libraryIncrementalBinaryTree{
uint8internalconstant MAX_DEPTH =32;
uint256internalconstant SNARK_SCALAR_FIELD =21888242871839275222246405745257275088548364400416034343698204186575808495617;
/// @dev Initializes a tree./// @param self: Tree data./// @param depth: Depth of the tree./// @param zero: Zero value to be used.functioninit(
IncrementalTreeData storageself,
uint256 depth,
uint256 zero
) public{
require(zero < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD");
require(depth >0&& depth <= MAX_DEPTH, "IncrementalBinaryTree: tree depth must be between 1 and 32");
self.depth = depth;
for (uint8 i =0; i < depth; ) {
self.zeroes[i] = zero;
zero = PoseidonT3.poseidon([zero, zero]);
unchecked {
++i;
}
}
self.root = zero;
}
/// @dev Inserts a leaf in the tree./// @param self: Tree data./// @param leaf: Leaf to be inserted.functioninsert(IncrementalTreeData storageself, uint256 leaf) public{
uint256 depth =self.depth;
require(leaf < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD");
require(self.numberOfLeaves <2**depth, "IncrementalBinaryTree: tree is full");
uint256 index =self.numberOfLeaves;
uint256 hash = leaf;
for (uint8 i =0; i < depth; ) {
if (index &1==0) {
self.lastSubtrees[i] = [hash, self.zeroes[i]];
} else {
self.lastSubtrees[i][1] = hash;
}
hash = PoseidonT3.poseidon(self.lastSubtrees[i]);
index >>=1;
unchecked {
++i;
}
}
self.root = hash;
self.numberOfLeaves +=1;
}
/// @dev Updates a leaf in the tree./// @param self: Tree data./// @param leaf: Leaf to be updated./// @param newLeaf: New leaf./// @param proofSiblings: Array of the sibling nodes of the proof of membership./// @param proofPathIndices: Path of the proof of membership.functionupdate(
IncrementalTreeData storageself,
uint256 leaf,
uint256 newLeaf,
uint256[] calldata proofSiblings,
uint8[] calldata proofPathIndices
) public{
require(newLeaf != leaf, "IncrementalBinaryTree: new leaf cannot be the same as the old one");
require(newLeaf < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: new leaf must be < SNARK_SCALAR_FIELD");
require(
verify(self, leaf, proofSiblings, proofPathIndices),
"IncrementalBinaryTree: leaf is not part of the tree"
);
uint256 depth =self.depth;
uint256 hash = newLeaf;
uint256 updateIndex;
for (uint8 i =0; i < depth; ) {
updateIndex |=uint256(proofPathIndices[i]) <<uint256(i);
if (proofPathIndices[i] ==0) {
if (proofSiblings[i] ==self.lastSubtrees[i][1]) {
self.lastSubtrees[i][0] = hash;
}
hash = PoseidonT3.poseidon([hash, proofSiblings[i]]);
} else {
if (proofSiblings[i] ==self.lastSubtrees[i][0]) {
self.lastSubtrees[i][1] = hash;
}
hash = PoseidonT3.poseidon([proofSiblings[i], hash]);
}
unchecked {
++i;
}
}
require(updateIndex <self.numberOfLeaves, "IncrementalBinaryTree: leaf index out of range");
self.root = hash;
}
/// @dev Removes a leaf from the tree./// @param self: Tree data./// @param leaf: Leaf to be removed./// @param proofSiblings: Array of the sibling nodes of the proof of membership./// @param proofPathIndices: Path of the proof of membership.functionremove(
IncrementalTreeData storageself,
uint256 leaf,
uint256[] calldata proofSiblings,
uint8[] calldata proofPathIndices
) public{
update(self, leaf, self.zeroes[0], proofSiblings, proofPathIndices);
}
/// @dev Verify if the path is correct and the leaf is part of the tree./// @param self: Tree data./// @param leaf: Leaf to be removed./// @param proofSiblings: Array of the sibling nodes of the proof of membership./// @param proofPathIndices: Path of the proof of membership./// @return True or false.functionverify(
IncrementalTreeData storageself,
uint256 leaf,
uint256[] calldata proofSiblings,
uint8[] calldata proofPathIndices
) privateviewreturns (bool) {
require(leaf < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD");
uint256 depth =self.depth;
require(
proofPathIndices.length== depth && proofSiblings.length== depth,
"IncrementalBinaryTree: length of path is not correct"
);
uint256 hash = leaf;
for (uint8 i =0; i < depth; ) {
require(
proofSiblings[i] < SNARK_SCALAR_FIELD,
"IncrementalBinaryTree: sibling node must be < SNARK_SCALAR_FIELD"
);
require(
proofPathIndices[i] ==1|| proofPathIndices[i] ==0,
"IncrementalBinaryTree: path index is neither 0 nor 1"
);
if (proofPathIndices[i] ==0) {
hash = PoseidonT3.poseidon([hash, proofSiblings[i]]);
} else {
hash = PoseidonT3.poseidon([proofSiblings[i], hash]);
}
unchecked {
++i;
}
}
return hash ==self.root;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 13 of 18: Pairing.sol
// Copyright 2017 Christian Reitwiessner// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.//// The following Pairing library is a modified version adapted to Semaphore.//// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;libraryPairing{
errorInvalidProof();
// The prime q in the base field F_q for G1uint256constant BASE_MODULUS =21888242871839275222246405745257275088696311157297823662689037894645226208583;
// The prime modulus of the scalar field of G1.uint256constant SCALAR_MODULUS =21888242871839275222246405745257275088548364400416034343698204186575808495617;
structG1Point {
uint256 X;
uint256 Y;
}
// Encoding of field elements is: X[0] * z + X[1]structG2Point {
uint256[2] X;
uint256[2] Y;
}
/// @return the generator of G1functionP1() publicpurereturns (G1Point memory) {
return G1Point(1, 2);
}
/// @return the generator of G2functionP2() publicpurereturns (G2Point memory) {
return
G2Point(
[
11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781
],
[
4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930
]
);
}
/// @return r the negation of p, i.e. p.addition(p.negate()) should be zero.functionnegate(G1Point memory p) publicpurereturns (G1Point memory r) {
if (p.X ==0&& p.Y ==0) {
return G1Point(0, 0);
}
// Validate input or revertif (p.X >= BASE_MODULUS || p.Y >= BASE_MODULUS) {
revert InvalidProof();
}
// We know p.Y > 0 and p.Y < BASE_MODULUS.return G1Point(p.X, BASE_MODULUS - p.Y);
}
/// @return r the sum of two points of G1functionaddition(G1Point memory p1, G1Point memory p2) publicviewreturns (G1Point memory r) {
// By EIP-196 all input is validated to be less than the BASE_MODULUS and form points// on the curve.uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
// solium-disable-next-line security/no-inline-assemblyassembly {
success :=staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60)
}
if (!success) {
revert InvalidProof();
}
}
/// @return r the product of a point on G1 and a scalar, i.e./// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.functionscalar_mul(G1Point memory p, uint256 s) publicviewreturns (G1Point memory r) {
// By EIP-196 the values p.X and p.Y are verified to be less than the BASE_MODULUS and// form a valid point on the curve. But the scalar is not verified, so we do that explicitly.if (s >= SCALAR_MODULUS) {
revert InvalidProof();
}
uint256[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
// solium-disable-next-line security/no-inline-assemblyassembly {
success :=staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60)
}
if (!success) {
revert InvalidProof();
}
}
/// Asserts the pairing check/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should succeedfunctionpairingCheck(G1Point[] memory p1, G2Point[] memory p2) publicview{
// By EIP-197 all input is verified to be less than the BASE_MODULUS and form elements in their// respective groups of the right order.if (p1.length!= p2.length) {
revert InvalidProof();
}
uint256 elements = p1.length;
uint256 inputSize = elements *6;
uint256[] memory input =newuint256[](inputSize);
for (uint256 i =0; i < elements; i++) {
input[i *6+0] = p1[i].X;
input[i *6+1] = p1[i].Y;
input[i *6+2] = p2[i].X[0];
input[i *6+3] = p2[i].X[1];
input[i *6+4] = p2[i].Y[0];
input[i *6+5] = p2[i].Y[1];
}
uint256[1] memory out;
bool success;
// solium-disable-next-line security/no-inline-assemblyassembly {
success :=staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
if (!success || out[0] !=1) {
revert InvalidProof();
}
}
}
Contract Source Code
File 14 of 18: SemaphoreGroups.sol
//SPDX-License-Identifier: MITpragmasolidity 0.8.4;import"../interfaces/ISemaphoreGroups.sol";
import"@zk-kit/incremental-merkle-tree.sol/IncrementalBinaryTree.sol";
import"@openzeppelin/contracts/utils/Context.sol";
/// @title Semaphore groups contract./// @dev This contract allows you to create groups, add, remove and update members./// You can use getters to obtain informations about groups (root, depth, number of leaves).abstractcontractSemaphoreGroupsisContext, ISemaphoreGroups{
usingIncrementalBinaryTreeforIncrementalTreeData;
/// @dev Gets a group id and returns the tree data.mapping(uint256=> IncrementalTreeData) internal merkleTrees;
/// @dev Creates a new group by initializing the associated tree./// @param groupId: Id of the group./// @param merkleTreeDepth: Depth of the tree.function_createGroup(uint256 groupId, uint256 merkleTreeDepth) internalvirtual{
if (getMerkleTreeDepth(groupId) !=0) {
revert Semaphore__GroupAlreadyExists();
}
// The zeroValue is an implicit member of the group, or an implicit leaf of the Merkle tree.// Although there is a remote possibility that the preimage of// the hash may be calculated, using this value we aim to minimize the risk.uint256 zeroValue =uint256(keccak256(abi.encodePacked(groupId))) >>8;
merkleTrees[groupId].init(merkleTreeDepth, zeroValue);
emit GroupCreated(groupId, merkleTreeDepth, zeroValue);
}
/// @dev Adds an identity commitment to an existing group./// @param groupId: Id of the group./// @param identityCommitment: New identity commitment.function_addMember(uint256 groupId, uint256 identityCommitment) internalvirtual{
if (getMerkleTreeDepth(groupId) ==0) {
revert Semaphore__GroupDoesNotExist();
}
merkleTrees[groupId].insert(identityCommitment);
uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);
uint256 index = getNumberOfMerkleTreeLeaves(groupId) -1;
emit MemberAdded(groupId, index, identityCommitment, merkleTreeRoot);
}
/// @dev Updates an identity commitment of an existing group. A proof of membership is/// needed to check if the node to be updated is part of the tree./// @param groupId: Id of the group./// @param identityCommitment: Existing identity commitment to be updated./// @param newIdentityCommitment: New identity commitment./// @param proofSiblings: Array of the sibling nodes of the proof of membership./// @param proofPathIndices: Path of the proof of membership.function_updateMember(uint256 groupId,
uint256 identityCommitment,
uint256 newIdentityCommitment,
uint256[] calldata proofSiblings,
uint8[] calldata proofPathIndices
) internalvirtual{
if (getMerkleTreeDepth(groupId) ==0) {
revert Semaphore__GroupDoesNotExist();
}
merkleTrees[groupId].update(identityCommitment, newIdentityCommitment, proofSiblings, proofPathIndices);
uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);
uint256 index = proofPathIndicesToMemberIndex(proofPathIndices);
emit MemberUpdated(groupId, index, identityCommitment, newIdentityCommitment, merkleTreeRoot);
}
/// @dev Removes an identity commitment from an existing group. A proof of membership is/// needed to check if the node to be deleted is part of the tree./// @param groupId: Id of the group./// @param identityCommitment: Existing identity commitment to be removed./// @param proofSiblings: Array of the sibling nodes of the proof of membership./// @param proofPathIndices: Path of the proof of membership.function_removeMember(uint256 groupId,
uint256 identityCommitment,
uint256[] calldata proofSiblings,
uint8[] calldata proofPathIndices
) internalvirtual{
if (getMerkleTreeDepth(groupId) ==0) {
revert Semaphore__GroupDoesNotExist();
}
merkleTrees[groupId].remove(identityCommitment, proofSiblings, proofPathIndices);
uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);
uint256 index = proofPathIndicesToMemberIndex(proofPathIndices);
emit MemberRemoved(groupId, index, identityCommitment, merkleTreeRoot);
}
/// @dev See {ISemaphoreGroups-getMerkleTreeRoot}.functiongetMerkleTreeRoot(uint256 groupId) publicviewvirtualoverridereturns (uint256) {
return merkleTrees[groupId].root;
}
/// @dev See {ISemaphoreGroups-getMerkleTreeDepth}.functiongetMerkleTreeDepth(uint256 groupId) publicviewvirtualoverridereturns (uint256) {
return merkleTrees[groupId].depth;
}
/// @dev See {ISemaphoreGroups-getNumberOfMerkleTreeLeaves}.functiongetNumberOfMerkleTreeLeaves(uint256 groupId) publicviewvirtualoverridereturns (uint256) {
return merkleTrees[groupId].numberOfLeaves;
}
/// @dev Converts the path indices of a Merkle proof to the identity commitment index in the tree./// @param proofPathIndices: Path of the proof of membership./// @return Index of a group member.functionproofPathIndicesToMemberIndex(uint8[] calldata proofPathIndices) privatepurereturns (uint256) {
uint256 memberIndex =0;
for (uint8 i =uint8(proofPathIndices.length); i >0; ) {
if (memberIndex >0|| proofPathIndices[i -1] !=0) {
memberIndex *=2;
if (proofPathIndices[i -1] ==1) {
memberIndex +=1;
}
}
unchecked {
--i;
}
}
return memberIndex;
}
}