S Price: $0.731677 (+8.72%)

Contract Diff Checker

Contract Name:
SRTickets

Contract Source Code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract JobBoard is ReentrancyGuard {
    // The amount of ETH to be paid per block for a job ad
    uint256 public amountPerBlock;
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for IERC20;
    address public owner;
    // The struct for a job ad
    struct JobAd {
        // The ID of the job ad
        uint256 id;
        // The title of the job ad
        string title;
        // The description of the job ad
        string description;
        // The URL where users can apply for the job
        string apply_url;
        // The expiring date of the job ad
        uint256 expiring_date;
        // Whether the job ad has been validated or not
        bool validated;
        //address of ad owner
        address owner;
        string tags;
    }

    struct Application {
        uint256 id;
        string github;
        string linkedin;
        uint256 jobId;
        bool validated;
        address owner;
    }

    // The mapping from job ad IDs to job ads
    mapping(uint256 => JobAd) public jobAds;
    mapping(uint256 => Application) public applications;

    //trustedAddresses are allowed to validate ads
    //and applications
    EnumerableSet.AddressSet trustedAddresses;

    // The counter for generating unique job ad IDs
    uint256 public jobAdCounter;
    uint256 public applicationCounter;

    // The constructor function
    constructor() {
        // Set the amountPerBlock to a default value of 1 ETH per block
        amountPerBlock = 1 ether;
    }

    modifier onlyOwner() {
        require(address(msg.sender) == owner, "!owner");
        _;
    }

    // The function to create a new job ad
    function createApplication(
        //this info (github and linkedin) will be encrypted in the frontend using
        //the public key of the ad owner and the the public key
        //of each validator
        string memory _github,
        string memory _linkedin,
        uint _jobId
    ) public payable {
        // Generate a unique ID for the job ad
        uint256 applicationId = applicationCounter++;

        // Create a new job ad with the specified parameters
        Application memory application = Application({
            id: applicationId,
            github: _github,
            linkedin: _linkedin,
            jobId: _jobId,
            validated: false,
            owner: msg.sender
        });
        applications[applicationId] = application;
    }

    // The function to create a new job ad
    function createAd(
        string memory _title,
        string memory _description,
        string memory _apply_url,
        uint256 _expiring_date,
        string memory _tags
    ) public payable {
        // Generate a unique ID for the job ad
        uint256 adId = jobAdCounter++;

        // Create a new job ad with the specified parameters
        JobAd memory ad = JobAd({
            id: adId,
            title: _title,
            description: _description,
            apply_url: _apply_url,
            expiring_date: _expiring_date,
            validated: true,
            tags: _tags,
            owner: msg.sender
        });

        // Save the new job ad
        jobAds[adId] = ad;

        // Calculate the fee to be paid for the job ad
        uint256 fee = amountPerBlock * (ad.expiring_date - block.number);

        // Require the user to pay the fee in ETH
        require(msg.value >= fee, "Insufficient ETH");
    }

    // The function to bump the expiring date of a job ad
    function bumpExpiringDate(
        uint256 _ad_id,
        uint256 _new_expiring_date
    ) public payable {
        // Get the job ad to bump the expiring date for
        JobAd storage ad = jobAds[_ad_id];

        // Update the expiring date of the job ad
        ad.expiring_date = _new_expiring_date;

        // Calculate the fee to be paid for extending the expiring date
        uint256 fee = amountPerBlock * (ad.expiring_date - block.number);

        // Require the user to pay the fee in ETH
        require(msg.value >= fee, "Insufficient ETH");
    }

    // The function to check if a job ad has expired
    function isExpired(uint256 _ad_id) public view returns (bool) {
        // Get the job ad to check
        JobAd storage ad = jobAds[_ad_id];

        // Return whether the job ad has expired or not
        return (ad.expiring_date <= block.number);
    }

    // The function to check if a job ad has been validated
    function isValidatedAd(uint256 _ad_id) public view returns (bool) {
        // Get the job ad to check
        JobAd storage ad = jobAds[_ad_id];

        return ad.validated;
    }

    // The function to check if an application has been validated
    function isValidatedApplication(
        uint256 _application_id
    ) public view returns (bool) {
        // Get the job ad to check
        Application storage application = applications[_application_id];

        return application.validated;
    }

    function validateAd(uint256 _ad_id) public {
        if (trustedAddresses.contains(msg.sender)) {
            JobAd storage ad = jobAds[_ad_id];
        }
    }

    function validateApplication(uint256 _application_id) public {
        if (trustedAddresses.contains(msg.sender)) {
            Application storage application = applications[_application_id];
            //    application.confirmations += application.confirmations;
        }
    }

    function distributeGains() public {}

    /***
     * @notice withdraw funds
     * This function allows owner to withdraw funds from contracts
     * @param _token address of token to withdraw
     * @param _amount amount to withdraw
     **/
    function withdraw(address _token, uint256 _amount) external onlyOwner {
        if (_token != address(0)) {
            IERC20(_token).safeTransfer(address(owner), _amount);
        } else {
            (bool ok, ) = owner.call{value: _amount}("");
            require(ok, "Failed");
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^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;`
 */
library Counters {
    struct Counter {
        // 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/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastvalue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastvalue;
                // Update the index for the moved value
                set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        return _values(set._inner);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/utils/SafeERC20.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";

/**
 * @title PaymentSplitter
 * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
 * that the Ether will be split in this way, since it is handled transparently by the contract.
 *
 * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
 * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
 * an amount proportional to the percentage of total shares they were assigned.
 *
 * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
 * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
 * function.
 *
 * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
 * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
 * to run tests before sending real value to this contract.
 */
contract PaymentSplitter is Context {
    event PayeeAdded(address account, uint256 shares);
    event PaymentReleased(address to, uint256 amount);
    event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
    event PaymentReceived(address from, uint256 amount);

    uint256 private _totalShares;
    uint256 private _totalReleased;

    mapping(address => uint256) private _shares;
    mapping(address => uint256) private _released;
    address[] private _payees;

    mapping(IERC20 => uint256) private _erc20TotalReleased;
    mapping(IERC20 => mapping(address => uint256)) private _erc20Released;

    /**
     * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
     * the matching position in the `shares` array.
     *
     * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
     * duplicates in `payees`.
     */
    constructor(address[] memory payees, uint256[] memory shares_) payable {
        require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
        require(payees.length > 0, "PaymentSplitter: no payees");

        for (uint256 i = 0; i < payees.length; i++) {
            _addPayee(payees[i], shares_[i]);
        }
    }

    /**
     * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
     * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
     * reliability of the events, and not the actual splitting of Ether.
     *
     * To learn more about this see the Solidity documentation for
     * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
     * functions].
     */
    receive() external payable virtual {
        emit PaymentReceived(_msgSender(), msg.value);
    }

    /**
     * @dev Getter for the total shares held by payees.
     */
    function totalShares() public view returns (uint256) {
        return _totalShares;
    }

    /**
     * @dev Getter for the total amount of Ether already released.
     */
    function totalReleased() public view returns (uint256) {
        return _totalReleased;
    }

    /**
     * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
     * contract.
     */
    function totalReleased(IERC20 token) public view returns (uint256) {
        return _erc20TotalReleased[token];
    }

    /**
     * @dev Getter for the amount of shares held by an account.
     */
    function shares(address account) public view returns (uint256) {
        return _shares[account];
    }

    /**
     * @dev Getter for the amount of Ether already released to a payee.
     */
    function released(address account) public view returns (uint256) {
        return _released[account];
    }

    /**
     * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
     * IERC20 contract.
     */
    function released(IERC20 token, address account) public view returns (uint256) {
        return _erc20Released[token][account];
    }

    /**
     * @dev Getter for the address of the payee number `index`.
     */
    function payee(uint256 index) public view returns (address) {
        return _payees[index];
    }

    /**
     * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
     * total shares and their previous withdrawals.
     */
    function release(address payable account) public virtual {
        require(_shares[account] > 0, "PaymentSplitter: account has no shares");

        uint256 totalReceived = address(this).balance + totalReleased();
        uint256 payment = _pendingPayment(account, totalReceived, released(account));

        require(payment != 0, "PaymentSplitter: account is not due payment");

        _released[account] += payment;
        _totalReleased += payment;

        Address.sendValue(account, payment);
        emit PaymentReleased(account, payment);
    }

    /**
     * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
     * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
     * contract.
     */
    function release(IERC20 token, address account) public virtual {
        require(_shares[account] > 0, "PaymentSplitter: account has no shares");

        uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
        uint256 payment = _pendingPayment(account, totalReceived, released(token, account));

        require(payment != 0, "PaymentSplitter: account is not due payment");

        _erc20Released[token][account] += payment;
        _erc20TotalReleased[token] += payment;

        SafeERC20.safeTransfer(token, account, payment);
        emit ERC20PaymentReleased(token, account, payment);
    }

    /**
     * @dev internal logic for computing the pending payment of an `account` given the token historical balances and
     * already released amounts.
     */
    function _pendingPayment(
        address account,
        uint256 totalReceived,
        uint256 alreadyReleased
    ) private view returns (uint256) {
        return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
    }

    /**
     * @dev Add a new payee to the contract.
     * @param account The address of the payee to add.
     * @param shares_ The number of shares owned by the payee.
     */
    function _addPayee(address account, uint256 shares_) private {
        require(account != address(0), "PaymentSplitter: account is the zero address");
        require(shares_ > 0, "PaymentSplitter: shares are 0");
        require(_shares[account] == 0, "PaymentSplitter: account already has shares");

        _payees.push(account);
        _shares[account] = shares_;
        _totalShares = _totalShares + shares_;
        emit PayeeAdded(account, shares_);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @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.
     * ====
     */
    function isContract(address account) internal view returns (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].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        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._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        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._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @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._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        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._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        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._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @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._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^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.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (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.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `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.
     */
    function approve(address spender, uint256 amount) external returns (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.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// SPDX-License-Identifier: MIT
//vedb25b
pragma solidity 0.8.15;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

contract ISRTickets {
    mapping(address => Counters.Counter) public attendeesCount;
}

contract NFTRemote {
    function mintItem(
        address attendee,
        string memory ticketName,
        string memory social
    ) public returns (uint256) {}

    function setCancelled(uint256 itemId) public {}

    function setSRTicketsDiscountsAddress(address _srtdiscount) public {}

    function setSocialTicket(
        string memory ticketName,
        string memory social,
        uint256 itemId
    ) public {}
}

contract SRTicketsDiscounts {
    using Counters for Counters.Counter;
    struct DiscountResponse {
        bool hasDiscountCode;
        bool hasDiscountAddress;
        bool hasTokenDiscount;
        uint256 discountAmount;
    }
    struct SenderAndTokenDiscountBuyer {
        address sender;
        bool tokenDiscountBuyer;
    }
    mapping(address => mapping(uint256 => Attendee)) private attendees;

    mapping(address => Counters.Counter) public attendeesCount;

    // attendee details, fields are encrypted on the frontend
    struct Attendee {
        string email;
        string fname;
        string lname;
        string bio;
        string job;
        string company;
        string social;
        string ticket;
        string discountCode;
        address tokenDiscount;
        address sender;
        address buyToken;
        uint256 pricePaid;
        uint256 pricePaidInToken;
        bool cancelled;
        uint256 refunded;
        bool allowResell;
        uint256 resellPrice;
        string code;
        uint256 boughtOn;
        bool resold;
        uint256 nftId;
    }

    // discount code details
    struct DiscountCode {
        uint256 qty;
        Counters.Counter used;
        uint256 amount;
        string code;
        uint256 endDate;
        uint256 startDate;
    }

    // discount address details, discount based on buyer address
    struct DiscountAddress {
        address buyer;
        uint256 qty;
        Counters.Counter used;
        uint256 amount;
        string code;
        uint256 endDate;
        uint256 startDate;
    }

    // discount token details, discount based on a buyer's token balance
    // can be used once only per buyer
    struct TokenDiscount {
        address token;
        uint256 minAmount;
        uint256 qty;
        Counters.Counter used;
        uint256 amount;
        uint256 endDate;
        uint256 startDate;
    }

    // @notice store address of ticket contract
    address public SRTicketsAddress;

    // @notice store address of contract owner
    address public owner;

    /// @notice stores address of nft contract
    address private nftContract;

    constructor() {
        owner = msg.sender;
    }

    event LogAttendee(
        address indexed attendeeAddress,
        uint256 attendeeIndex,
        string message
    );
    event LogResell(
        address indexed buyerAddress,
        address sellerAddress,
        uint256 buyerIndex,
        uint256 sellerIndex,
        string message
    );

    /***
     * @notice set ticket contract address
     * This function allows owner to set contract ticket address
     * @param _newAddr contract address
     **/
    function setSRTicketsAddress(address _newAddr) public {
        require(msg.sender == owner, "not owner");
        SRTicketsAddress = _newAddr;
    }

    /***
     * @notice set nft contract address
     * This function allows owner to set nft contract  address
     * @param _newAddr contract address
     **/
    function setNFTContract(address _newAddr) public {
        require(msg.sender == owner, "not owner");
        nftContract = _newAddr;
    }

    /***
     * @notice set attendee details
     * This function sets Attendee details by address and index
     * @param _attendeeIndex index of attendee
     * @param _newAttendee new attendee struct
     * @param _attendee current attendee struct
     * @param _sender Address of attendee
     * @param _resell true if this operation is a resell of the attendee's ticket
     * @param _isRefund true if this operation is a refund of the attendee's ticket
     **/
    function setAttendee(
        uint256 attendeeIndex,
        Attendee memory newAttendee,
        Attendee memory attendee,
        address sender,
        bool resell,
        bool refund
    ) public {
        require(
            msg.sender == SRTicketsAddress,
            string.concat(
                Strings.toHexString(uint160(msg.sender), 20),
                " not allowed, required ",
                Strings.toHexString(uint160(SRTicketsAddress), 20)
            )
        );
        Attendee memory exAttendee = attendee;
        bool updateSocialTicket = false;
        if (
            !stringsEquals(exAttendee.social, newAttendee.social) ||
            !stringsEquals(exAttendee.ticket, newAttendee.ticket)
        ) {
            updateSocialTicket = true;
        }
        attendee.email = newAttendee.email;
        attendee.fname = newAttendee.fname;
        attendee.lname = newAttendee.lname;
        attendee.social = newAttendee.social;
        attendee.bio = newAttendee.bio;
        attendee.job = newAttendee.job;
        attendee.company = newAttendee.company;
        attendee.allowResell = newAttendee.allowResell;
        attendee.resellPrice = newAttendee.resellPrice;
        attendee.ticket = newAttendee.ticket;

        if (refund) {
            attendee.refunded = newAttendee.refunded;
            attendee.cancelled = newAttendee.cancelled;
        }
        if (resell) {
            attendees[exAttendee.sender][attendeeIndex].cancelled = true;
            attendees[exAttendee.sender][attendeeIndex].allowResell = false;
            //set old attendee nft as cancelled
            NFTRemote nc = NFTRemote(nftContract);
            nc.setCancelled(attendees[exAttendee.sender][attendeeIndex].nftId);

            uint256 oldAttendeeIndex = attendeeIndex;
            attendee.code = newAttendee.code;
            attendee.sender = sender;
            attendee.cancelled = false;

            attendee.allowResell = false;
            attendee.resellPrice = 0;
            attendee.resold = true;
            // mint new nft for new owner
            uint256 nftId = nc.mintItem(
                attendee.sender,
                attendee.ticket,
                attendee.social
            );
            attendee.nftId = nftId;

            emit LogResell(
                sender,
                exAttendee.sender,
                attendeeIndex,
                oldAttendeeIndex,
                "resell"
            );
        }
        if (updateSocialTicket) {
            NFTRemote ncupdated = NFTRemote(nftContract);
            ncupdated.setSocialTicket(
                attendee.ticket,
                attendee.social,
                attendee.nftId
            );
        }
        attendees[sender][attendeeIndex] = attendee;
        emit LogAttendee(sender, attendeeIndex, "setAttendee");
    }

    /***
     * @notice get discount code amount for an attendee
     * This function checks discount code amount
     * @params _discountCodeTicketAttendee defines whether attendee has a discount code
     * @params _dcQty how many discount in total
     * @params _dcStartDate Timestamp of date at which discount can start being used
     * @params _dcEndDate Timestamp of date at which discount won't be available anymore
     * @params _dcUsed Amount of discount used
     * @params _dcAmount Amount of the discount in percentage (eg. 5 for a 5% discount)
     **/
    function getDiscountCodeAmount(
        bool _discountCodeTicketAttendee,
        uint256 _dcQty,
        uint256 _dcStartDate,
        uint256 _dcEndDate,
        uint256 _dcUsed,
        uint256 _dcAmount
    ) public view returns (uint256, bool found) {
        uint256 discountAmount = 0;

        if (_discountCodeTicketAttendee) {
            if (
                _dcUsed < _dcQty &&
                _dcStartDate < block.timestamp &&
                _dcEndDate > block.timestamp
            ) {
                discountAmount = _dcAmount;
                found = true;
            }
        }
        return (discountAmount, found);
    }

    /***
     * @notice get discount address amount for an attendee
     * This function checks discount address amount (discount based on sender address)
     * @params _discountAddressTicketAttendee true if attendee has a discount based on address
     * @params _dcQty how many discount in total
     * @params _dcStartDate Timestamp of date at which discount can start being used
     * @params _dcEndDate Timestamp of date at which discount won't be available anymore
     * @params _dcUsed Amount of discount used
     * @params _dcAmount Amount of the discount in percentage (eg. 5 for a 5% discount)
     **/
    function getDiscountAddressAmount(
        bool _discountAddressTicketAttendee,
        uint256 _daQty,
        uint256 _daStartDate,
        uint256 _daEndDate,
        uint256 _daUsed,
        uint256 _daAmount,
        uint256 _discountAmount
    ) public view returns (uint256, bool found) {
        if (_discountAddressTicketAttendee) {
            if (
                _daQty > _daUsed &&
                _daStartDate < block.timestamp &&
                _daEndDate > block.timestamp &&
                _daAmount > _discountAmount &&
                _daAmount > 0
            ) {
                return (_daAmount, true);
            }
        }
        return (_discountAmount, found);
    }

    /***
     * @notice get token discount amount for an attendee
     * This function checks token discount amount (discount based on sender token balance)
     * @params _stdb struct with attendee address and whether it has a token discount
     * @params _discountAmount Amount of the discount in percentage (eg. 5 for a 5% discount)
     * @params _tokenDiscountTicketAttendee checks if a ticket has a token discount associated
     * @params _ts token discount struct
     * @params _tokenDiscountAttendee address of the token used for discount
     **/
    function getTokenDiscountAmount(
        SenderAndTokenDiscountBuyer memory _stdb,
        uint256 _discountAmount,
        bool _tokenDiscountTicketAttendee,
        TokenDiscount memory _ts,
        address _tokenDiscountAttendee
    ) public view returns (uint256, bool found) {
        if (
            _tokenDiscountAttendee != address(0) && _tokenDiscountTicketAttendee
        ) {
            //check sender balance
            IERC20 tokenDiscount = IERC20(_tokenDiscountAttendee);
            uint256 balance = tokenDiscount.balanceOf(_stdb.sender);

            if (
                (balance > _ts.minAmount &&
                    _ts.used._value < _ts.qty &&
                    _ts.startDate < block.timestamp &&
                    _ts.endDate > block.timestamp &&
                    _ts.amount > _discountAmount &&
                    !_stdb.tokenDiscountBuyer)
            ) {
                return (_ts.amount, true);
            }
        }

        return (_discountAmount, found);
    }

    /***
     * @notice get discount amount for an attendee
     * This function checks each kind of discount and returns total discount amount
     * @params _stdb struct with attendee address and whether it has a token discount
     * @params _discountCodeTicketAttendee true if a discount code applies to a given ticket
     * @params _dc discount code
     * @params _discountAddressTicketAttendee true if attendee has a discount based on address
     * @params _da discount address
     * @params _tokenDiscountTicketAttendee address of the token used for discount
     * @params _ts token discount struct
     * @params _tokenDiscountAttendee address of the token used for discount
     **/
    function getDiscountView(
        SenderAndTokenDiscountBuyer memory _stdb,
        bool _discountCodeTicketAttendee,
        DiscountCode memory _dc,
        bool _discountAddressTicketAttendee,
        DiscountAddress memory _da,
        bool _tokenDiscountTicketAttendee,
        TokenDiscount memory _ts,
        address _tokenDiscountAttendee
    ) public view returns (DiscountResponse memory) {
        //check sender Discount code
        uint256 discountAmount = 0;
        DiscountResponse memory dr;
        (discountAmount, dr.hasDiscountCode) = getDiscountCodeAmount(
            _discountCodeTicketAttendee,
            _dc.qty,
            _dc.startDate,
            _dc.endDate,
            _dc.used._value,
            _dc.amount
        );
        (discountAmount, dr.hasDiscountAddress) = getDiscountAddressAmount(
            _discountAddressTicketAttendee,
            _da.qty,
            _da.startDate,
            _da.endDate,
            _da.used._value,
            _da.amount,
            discountAmount
        );
        if (dr.hasDiscountAddress) {
            dr.hasDiscountCode = false;
        }
        (discountAmount, dr.hasTokenDiscount) = getTokenDiscountAmount(
            _stdb,
            discountAmount,
            _tokenDiscountTicketAttendee,
            _ts,
            _tokenDiscountAttendee
        );
        if (dr.hasTokenDiscount) {
            dr.hasDiscountAddress = false;
            dr.hasDiscountCode = false;
        }
        dr.discountAmount = discountAmount;
        return dr;
    }

    /***
     * @notice retrieve attendee details
     * This function gets Attendee details by address and index
     * @param _sender Address of attendee
     * @param _index Attendee ticket index (each attendee can have more than one ticket)
     **/
    function getAttendee(
        address sender,
        uint256 index
    ) public view returns (Attendee memory) {
        //SRTicketsRemote str = SRTicketsRemote(sender);
        //Attendee memory x = str.attendees(sender, index);
        return attendees[sender][index];
    }

    /***
     * @notice retrieve attendee's total spent
     * This function gets Attendee total spent on tickets
     * @param _sender Address of attendee
     **/
    function getAttendeeSpent(address sender) public view returns (uint256) {
        ISRTickets sr = ISRTickets(SRTicketsAddress);
        uint256 count = sr.attendeesCount(sender);
        uint256 totalPaidInToken = 0;
        for (uint256 i = 0; i < count; i++) {
            totalPaidInToken += attendees[sender][i].pricePaidInToken;
        }

        return totalPaidInToken;
    }
}

function stringsEquals(string memory s1, string memory s2) pure returns (bool) {
    bytes memory b1 = bytes(s1);
    bytes memory b2 = bytes(s2);
    uint256 l1 = b1.length;
    if (l1 != b2.length) return false;
    for (uint256 i = 0; i < l1; i++) {
        if (b1[i] != b2[i]) return false;
    }
    return true;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits a {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` 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 from,
        address to,
        uint256 tokenId
    ) internal virtual {}

    /**
     * @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.
     * - `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(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "./IERC721Enumerable.sol";

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, tokenId);

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
//vedb52
pragma solidity 0.8.15;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

contract SRTicketsNFT is ERC721Enumerable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;
    mapping(uint256 => string) public socials;
    mapping(uint256 => string) public cancelled;
    mapping(uint256 => string) public ticketNames;
    mapping(uint256 => address) public owners;

    string public baseURI;
    string public chainName;
    address public coowner;
    address public owner;
    // @notice store address of ticket contract
    address public SRTicketsDiscountsAddress;

    constructor(string memory _chainName) ERC721("ETHDubai 2025", "EDB25") {
        baseURI = "https://ed2025.vercel.app/nftimage.svg";
        chainName = _chainName;
        owner = msg.sender;
    }
    function addressToString(
        address _addr
    ) public pure returns (string memory) {
        bytes memory buffer = new bytes(40);
        for (uint256 i = 0; i < 20; i++) {
            bytes1 b = bytes1(uint8(uint160(_addr) / (2 ** (8 * (19 - i)))));
            bytes1 hi = bytes1(uint8(b) / 16);
            bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
            buffer[2 * i] = char(hi);
            buffer[2 * i + 1] = char(lo);
        }
        return string(abi.encodePacked("0x", buffer));
    }

    function char(bytes1 b) internal pure returns (bytes1) {
        if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
        else return bytes1(uint8(b) + 0x57);
    }
    function setOwner(address _owner) public {
        require(msg.sender == coowner || msg.sender == owner, "not allowed1");
        owner = _owner;
    }

    function setCoOwner(address _coowner) public {
        require(msg.sender == coowner || msg.sender == owner, "not allowed2");
        coowner = _coowner;
    }

    function setSRTicketsDiscountsAddress(address _srtdiscount) public {
        require(msg.sender == coowner || msg.sender == owner, "not allowed3");
        SRTicketsDiscountsAddress = _srtdiscount;
    }

    function setChain(string memory _chainName) public {
        require(msg.sender == coowner || msg.sender == owner, "not allowed4");
        chainName = _chainName;
    }

    function setBaseURI(string memory _baseURI) public {
        require(msg.sender == coowner || msg.sender == owner, "not allowed5");
        baseURI = _baseURI;
    }

    function setCancelled(uint256 itemId) public {
        require(
            msg.sender == coowner ||
                msg.sender == owner ||
                msg.sender == SRTicketsDiscountsAddress,
            "not allowed6"
        );
        cancelled[itemId] = "true";
    }

    function setSocialTicket(
        string memory ticketName,
        string memory social,
        uint256 itemId
    ) public {
        require(
            msg.sender == coowner ||
                msg.sender == owner ||
                msg.sender == SRTicketsDiscountsAddress,
            "not allowed7"
        );
        ticketNames[itemId] = ticketName;
        socials[itemId] = social;
    }

    function mintItem(
        address _attendee,
        string memory _ticketName,
        string memory _social
    ) public returns (uint256) {
        require(
            msg.sender == coowner ||
                msg.sender == owner ||
                msg.sender == SRTicketsDiscountsAddress,
            addressToString(msg.sender)
        );
        _tokenIds.increment();
        uint256 newItemId = _tokenIds.current();
        _mint(_attendee, newItemId);
        socials[newItemId] = _social;
        owners[newItemId] = _attendee;
        ticketNames[newItemId] = _ticketName;
        cancelled[newItemId] = "false";
        return newItemId;
    }

    function tokenURI(
        uint256 tokenId
    ) public view virtual override returns (string memory) {
        require(
            tokenId <= _tokenIds.current(),
            "ERC721Metadata: URI query for nonexistent token"
        );

        string memory uri = string.concat(
            baseURI,
            "?c=",
            chainName,
            "&id=",
            Strings.toString(tokenId),
            "&s=",
            socials[tokenId],
            "&t=",
            ticketNames[tokenId],
            "&cl=",
            cancelled[tokenId]
        );
        return uri;
    }
}

// SPDX-License-Identifier: MIT
//vedb25sonic2
pragma solidity 0.8.15;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract NFTRemote {
    function mintItem(
        address attendee,
        string memory ticketName,
        string memory social
    ) public returns (uint256) {}

    function setCancelled(uint256 itemId) public {}
}

contract SRTicketsDiscountsRemote {
    struct DiscountResponse {
        bool hasDiscountCode;
        bool hasDiscountAddress;
        bool hasTokenDiscount;
        uint256 discountAmount;
    }
    address public SRTicketsAddress;

    struct SenderAndTokenDiscountBuyer {
        address sender;
        bool tokenDiscountBuyer;
    }

    function getAttendee(
        address sender,
        uint256 index
    ) public view returns (SRTickets.Attendee memory) {}

    function getDiscountView(
        SenderAndTokenDiscountBuyer memory stdb,
        bool discountCodeTicketAttendee,
        SRTickets.DiscountCode memory,
        bool discountAddressTicketAttendee,
        SRTickets.DiscountAddress memory,
        bool tokenDiscountTicketAttendee,
        SRTickets.TokenDiscount memory,
        address tokenDiscountAttendee
    ) public view returns (DiscountResponse memory) {}

    function setAttendee(
        uint256 attendeeIndex,
        SRTickets.Attendee memory newAttendee,
        SRTickets.Attendee memory attendee,
        address sender,
        bool resell,
        bool refund
    ) public {}
}

contract SRTickets is ReentrancyGuard {
    using Counters for Counters.Counter;
    using SafeERC20 for IERC20;

    /**********
     * Events
     **********/
    event LMint(
        address indexed attendeeAddress,
        Attendee attendee,
        string message
    );
    event LogBuy(
        address indexed attendee,
        uint256 amount,
        uint256 amountUSD,
        address token
    );
    event LogRefund(
        address indexed attendee,
        uint256 amount,
        uint256 attendeesIndex,
        address buyToken
    );

    event LogSetOwner(address indexed sender, address newOwner);

    /***********
     * Variables
     ***********/

    // an address of the owner
    address public owner;

    // an address of the to be confirmed owner
    address public tbcOwner;

    // when true, people can call the selfRefund function to get a refund
    bool public allowSelfRefund;

    // when true, people can buy resellable tickets
    bool public allowBuyResellable;

    // amount by which self-refund decrease every x second
    uint256 public refundIncFee;

    // time lapse between each self-refund amount decrease
    uint256 public refundIncLapse;

    // refund fee
    uint256 public refundFee;

    // fee charged when reselling ticket
    uint256 public resellFee;

    // ticket struct details
    struct Ticket {
        uint256 qty;
        Counters.Counter used;
        uint256 price;
        uint256 endDate;
        uint256 startDate;
    }

    // discount code details
    struct DiscountCode {
        uint256 qty;
        Counters.Counter used;
        uint256 amount;
        string code;
        uint256 endDate;
        uint256 startDate;
    }

    // discount address details, discount based on buyer address
    struct DiscountAddress {
        address buyer;
        uint256 qty;
        Counters.Counter used;
        uint256 amount;
        string code;
        uint256 endDate;
        uint256 startDate;
    }

    // discount token details, discount based on a buyer's token balance
    // can be used once only per buyer
    struct TokenDiscount {
        address token;
        uint256 minAmount;
        uint256 qty;
        Counters.Counter used;
        uint256 amount;
        uint256 endDate;
        uint256 startDate;
    }

    // attendee details, fields are encrypted on the frontend
    struct Attendee {
        string email;
        string fname;
        string lname;
        string bio;
        string job;
        string company;
        string social;
        string ticket;
        string discountCode;
        address tokenDiscount;
        address sender;
        address buyToken;
        uint256 pricePaid;
        uint256 pricePaidInToken;
        bool cancelled;
        uint256 refunded;
        bool allowResell;
        uint256 resellPrice;
        string code;
        uint256 boughtOn;
        bool resold;
        uint256 nftId;
    }

    /**********
     * Mappings
     **********/
    /// @notice keeps track of list of tickets
    mapping(string => Ticket) public tickets;

    /// @notice keeps track of list of discount codes
    mapping(string => DiscountCode) public discountCodes;

    /// @notice keeps track of list of discount addresses
    mapping(address => DiscountAddress) public discountAddresses;

    /// @notice keeps track of list of token discounts
    mapping(address => TokenDiscount) public tokenDiscounts;

    /// @notice keeps track of list of token discounts for each ticket
    /// @dev mapping(token address => mapping(ticket => bool))
    mapping(address => mapping(string => bool)) public tokenDiscountTickets;

    /// @notice keeps track of list of token discounts for each buyer. Can be used once only per buyer.
    /// @dev mapping(token address => mapping(buyer address => bool))
    mapping(address => mapping(address => bool)) public tokenDiscountBuyer;

    /// @notice keeps track of list of discounts code for each ticket
    /// @dev mapping(discount code => mapping(ticket => bool))
    mapping(string => mapping(string => bool)) public discountCodeTickets;

    /// @notice keeps track of list of address discounts for each ticket
    /// @dev mapping(discount address => mapping(ticket => bool))
    mapping(address => mapping(string => bool)) public discountAddressTickets;

    /// @notice keeps track of list of chainlink price feeds
    mapping(address => address) public priceFeeds;

    /// @notice stores address of discount contract
    address private discountContract;

    /// @notice stores address of nft contract
    address private nftContract;

    /// @notice store total number of tickets per attendee
    mapping(address => Counters.Counter) public attendeesCount;

    constructor(address _discountContract, address _nftContract) {
        discountContract = _discountContract;
        nftContract = _nftContract;
        owner = address(msg.sender);
        allowSelfRefund = true;
        refundFee = 15;
        resellFee = 15;
        refundIncFee = 3;
        refundIncLapse = 1 days;
        //remove for prod
        //setTicket(100, 100 * 10**8, 9949326229, 1, "conference-only");
        //setTicket(25, 50, 9949326229, 1, "iftar-meetup");

        //priceFeeds[address(0)] = 0x7f8847242a530E809E17bF2DA5D2f9d2c4A43261; //kovan optimism
        //priceFeeds[address(0)] = 0x13e3Ee699D1909E989722E753853AE30b17e08c5; //mainnet optimism
        //priceFeeds[address(0)] = 0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612; //mainnet arbitrum
        /*       setTicket(100, 28750 * 10**6, 9949326229, 1, "modular-blockchain-conf");
        setTicket(
            100,
            46000 * 10**6,
            9949326229,
            1,
            "modular-blockchain-conf-party"
        );
        setTicket(
            100,
            138000 * 10**6,
            9949326229,
            1,
            "modular-blockchain-vc-conf-party"
        );

        setTicket(
            100,
            149500 * 10**6,
            9949326229,
            1,
            "modular-blockchain-conf-hotel"
        );
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "modular-blockchain-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "modular-blockchain-vc-conf-party-hotel"
        );

        setTicket(100, 28750 * 10**6, 9949326229, 1, "metamask-conf");
        setTicket(100, 46000 * 10**6, 9949326229, 1, "metamask-conf-party");
        setTicket(100, 138000 * 10**6, 9949326229, 1, "metamask-vc-conf-party");

        setTicket(100, 149500 * 10**6, 9949326229, 1, "metamask-conf-hotel");
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "metamask-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "metamask-vc-conf-party-hotel"
        );

        setTicket(100, 28750 * 10**6, 9949326229, 1, "verilog-conf");
        setTicket(100, 46000 * 10**6, 9949326229, 1, "verilog-conf-party");
        setTicket(100, 138000 * 10**6, 9949326229, 1, "verilog-vc-conf-party");

        setTicket(100, 149500 * 10**6, 9949326229, 1, "verilog-conf-hotel");
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "verilog-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "verilog-vc-conf-party-hotel"
        );

        setTicket(
            100,
            28750 * 10**6,
            9949326229,
            1,
            "build-fuelvm-exchange-conf"
        );
        setTicket(
            100,
            46000 * 10**6,
            9949326229,
            1,
            "build-fuelvm-exchange-conf-party"
        );
        setTicket(
            100,
            138000 * 10**6,
            9949326229,
            1,
            "build-fuelvm-exchange-vc-conf-party"
        );

        setTicket(
            100,
            149500 * 10**6,
            9949326229,
            1,
            "build-fuelvm-exchange-conf-hotel"
        );
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "build-fuelvm-exchange-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "build-fuelvm-exchange-vc-conf-party-hotel"
        );
*/

        /*
        setTicket(100, 28750 * 10**6, 9949326229, 1, "web3-intro-conf");
        setTicket(100, 46000 * 10**6, 9949326229, 1, "web3-intro-conf-party");
        setTicket(
            100,
            138000 * 10**6,
            9949326229,
            1,
            "web3-intro-vc-conf-party"
        );

        setTicket(100, 149500 * 10**6, 9949326229, 1, "web3-intro-conf-hotel");
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "web3-intro-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "web3-intro-vc-conf-party-hotel"
        );

        setTicket(100, 28750 * 10**6, 9949326229, 1, "moralis-conf");
        setTicket(100, 46000 * 10**6, 9949326229, 1, "moralis-conf-party");
        setTicket(100, 138000 * 10**6, 9949326229, 1, "moralis-vc-conf-party");

        setTicket(100, 149500 * 10**6, 9949326229, 1, "moralis-conf-hotel");
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "moralis-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "moralis-vc-conf-party-hotel"
        );
        setTicket(
            100,
            0x1010b87200,
            9949326229,
            1,
            "modular-blockchain-vc-conf"
        );
        setTicket(100, 0x1010b87200, 9949326229, 1, "verilog-vc-conf");
        setTicket(100, 0x1010b87200, 9949326229, 1, "web3-intro-vc-conf");
        setTicket(
            100,
            0x1010b87200,
            9949326229,
            1,
            "build-fuelvm-exchange-vc-conf"
        );
        setTicket(
            100,
            28750 * 10**6,
            9949326229,
            1,
            "partnering-with-giants-conf"
        );
        setTicket(
            100,
            138000 * 10**6,
            9949326229,
            1,
            "partnering-with-giants-vc-conf-party"
        );
        setTicket(
            100,
            149500 * 10**6,
            9949326229,
            1,
            "partnering-with-giants-conf-hotel"
        );
        setTicket(
            100,
            207000 * 10**6,
            9949326229,
            1,
            "partnering-with-giants-conf-party-hotel"
        );
        setTicket(
            100,
            287500 * 10**6,
            9949326229,
            1,
            "partnering-with-giants-vc-conf-party-hotel"
        );
        */
        ////mainnet
        /*
        priceFeeds[address(0)] = 0x4BAD96DD1C7D541270a0C92e1D4e5f12EEEA7a57; //mainnet
        //WETH
        priceFeeds[
            0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
        ] = 0x4BAD96DD1C7D541270a0C92e1D4e5f12EEEA7a57; //WETH mainnet
        //usdt
        priceFeeds[
            0xdAC17F958D2ee523a2206206994597C13D831ec7
        ] = 0x3E7d1eAB13ad0104d2750B8863b489D65364e32D;
        //dai
        priceFeeds[
            0x6B175474E89094C44Da98b954EedeAC495271d0F
        ] = 0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9;
        //usdc
        priceFeeds[
            0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
        ] = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4;
        //rai
        priceFeeds[
            0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919
        ] = 0x483d36F6a1d063d580c7a24F9A42B346f3a69fbb;
        //sushi
        priceFeeds[
            0x6B3595068778DD592e39A122f4f5a5cF09C90fE2
        ] = 0xCc70F09A6CC17553b2E31954cD36E4A2d89501f7;
        //LUSD
        priceFeeds[
            0x5f98805A4E8be255a32880FDeC7F6728C6568bA0
        ] = 0x3D7aE7E594f2f2091Ad8798313450130d0Aba3a0;
        //MIM
        priceFeeds[
            0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3
        ] = 0x7A364e8770418566e3eb2001A96116E6138Eb32F;
        //xsushi
        priceFeeds[
            0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272
        ] = 0xCC1f5d9e6956447630d703C8e93b2345c2DE3D13;
        //mkr
        priceFeeds[
            0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2
        ] = 0xec1D1B3b0443256cc3860e24a46F108e699484Aa;
        //yfi
        priceFeeds[
            0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e
        ] = 0xA027702dbb89fbd58938e4324ac03B58d812b0E1;
        //comp
        priceFeeds[
            0xc00e94Cb662C3520282E6f5717214004A7f26888
        ] = 0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5;
        //matic
        priceFeeds[
            0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0
        ] = 0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676;
        //1inch
        priceFeeds[
            0x111111111117dC0aa78b770fA6A738034120C302
        ] = 0xc929ad75B72593967DE83E7F7Cda0493458261D9;
        //busd
        priceFeeds[
            0x4Fabb145d64652a948d72533023f6E7A623C7C53
        ] = 0x833D8Eb16D306ed1FbB5D7A2E019e106B960965A;

        OPTIMISM
        priceFeeds[address(0)] = 0x13e3Ee699D1909E989722E753853AE30b17e08c5; //mainnet
        //WETH
        priceFeeds[
            0x4200000000000000000000000000000000000006
        ] = 0x13e3Ee699D1909E989722E753853AE30b17e08c5; //WETH mainnet
        //usdt
        priceFeeds[
            0x94b008aA00579c1307B0EF2c499aD98a8ce58e58
        ] = 0xECef79E109e997bCA29c1c0897ec9d7b03647F5E;
        //dai
        priceFeeds[
            0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1
        ] = 0x8dBa75e83DA73cc766A7e5a0ee71F656BAb470d6;
        //usdc
        priceFeeds[
            0x7F5c764cBc14f9669B88837ca1490cCa17c31607
        ] = 0x16a9FA2FDa030272Ce99B29CF780dFA30361E0f3;

        /*ARBITRUM*
        priceFeeds[address(0)] = 0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612;
        //WETH
        priceFeeds[
            0x82aF49447D8a07e3bd95BD0d56f35241523fBab1
        ] = 0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612; //WETH mainnet
        //usdt
        priceFeeds[
            0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9
        ] = 0x3f3f5dF88dC9F13eac63DF89EC16ef6e7E25DdE7;
        //dai
        priceFeeds[
            0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1
        ] = 0xc5C8E77B397E531B8EC06BFb0048328B30E9eCfB;
        //usdc
        priceFeeds[
            0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8
        ] = 0x50834F3163758fcC1Df9973b6e91f0F0F0434aD3;
        //sushi
        priceFeeds[
            0xd4d42F0b6DEF4CE0383636770eF773390d85c61A
        ] = 0xb2A8BA74cbca38508BA1632761b56C897060147C;
        //MIM
        priceFeeds[
            0xFEa7a6a0B346362BF88A9e4A88416B77a57D6c2A
        ] = 0x87121F6c9A9F6E90E59591E4Cf4804873f54A95b;

        arbitrum*/

        /****polygon
        priceFeeds[address(0)] = 0xAB594600376Ec9fD91F8e885dADF0CE036862dE0; //mainnet
        //WETH
        priceFeeds[
            0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619
        ] = 0xF9680D99D6C9589e2a93a78A04A279e509205945; //WETH mainnet
        //usdt
        priceFeeds[
            0xc2132D05D31c914a87C6611C10748AEb04B58e8F
        ] = 0x0A6513e40db6EB1b165753AD52E80663aeA50545;
        //dai
        priceFeeds[
            0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063
        ] = 0x4746DeC9e833A82EC7C2C1356372CcF2cfcD2F3D;
        //usdc
        priceFeeds[
            0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174
        ] = 0xfE4A8cc5b5B2366C1B58Bea3858e81843581b2F7;
        //rai
        priceFeeds[
            0x00e5646f60AC6Fb446f621d146B6E1886f002905
        ] = 0x7f45273fD7C644714825345670414Ea649b50b16;
        //sushi
        priceFeeds[
            0x0b3F868E0BE5597D5DB7fEB59E1CADBb0fdDa50a
        ] = 0x49B0c695039243BBfEb8EcD054EB70061fd54aa0;

        polygon */
        /******bsc
        priceFeeds[address(0)] = 0x0567F2323251f0Aab15c8dFb1967E4e8A7D42aeE; //mainnet
        //WETH
        priceFeeds[
            0x2170Ed0880ac9A755fd29B2688956BD959F933F8
        ] = 0x9ef1B8c0E4F7dc8bF5719Ea496883DC6401d5b2e; //WETH mainnet
        //usdt
        priceFeeds[
            0x55d398326f99059fF775485246999027B3197955
        ] = 0xB97Ad0E74fa7d920791E90258A6E2085088b4320;
        //dai
        priceFeeds[
            0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3
        ] = 0x132d3C0B1D2cEa0BC552588063bdBb210FDeecfA;
        //usdc
        priceFeeds[
            0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d
        ] = 0x51597f405303C4377E36123cBc172b13269EA163;

        //sushi
        priceFeeds[
            0x947950BcC74888a40Ffa2593C5798F11Fc9124C4
        ] = 0x49B0c695039243BBfEb8EcD054EB70061fd54aa0;
        //MIM
        priceFeeds[
            0xfE19F0B51438fd612f6FD59C1dbB3eA319f433Ba
        ] = 0xc9D267542B23B41fB93397a93e5a1D7B80Ea5A01;

        bsc*/

        /******ftm
        priceFeeds[address(0)] = 0xf4766552D15AE4d256Ad41B6cf2933482B0680dc; //mainnet
        //WETH
        priceFeeds[
            0xA59982c7A272839cBd93e02Bd8978E9a78189AB5
        ] = 0x11DdD3d147E5b83D01cee7070027092397d63658; //WETH mainnet
        //usdt
        priceFeeds[
           0x049d68029688eAbF473097a2fC38ef61633A3C7A
        ] = 0xF64b636c5dFe1d3555A847341cDC449f612307d0;
        //dai
        priceFeeds[
            0x8D11eC38a3EB5E956B052f67Da8Bdc9bef8Abf3E
        ] = 0x91d5DEFAFfE2854C7D02F50c80FA1fdc8A721e52;
        //usdc
        priceFeeds[
           0x04068DA6C83AFCFA0e13ba15A6696662335D5B75
        ] = 0x2553f4eeb82d5A26427b8d1106C51499CBa5D99c;
        //MIM
        priceFeeds[
           0x82f0B8B456c1A451378467398982d4834b6829c1
        ] = 0x28de48D3291F31F839274B8d82691c77DF1c5ceD;

        ftm*/

        /***avax
        priceFeeds[address(0)] = 0x0A77230d17318075983913bC2145DB16C7366156; //mainnet
        //WETH
        priceFeeds[
            0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB
        ] = 0x976B3D034E162d8bD72D6b9C989d545b839003b0; //WETH mainnet
        //usdt
        priceFeeds[
            0xde3A24028580884448a5397872046a019649b084
        ] = 0xEBE676ee90Fe1112671f19b6B7459bC678B67e8a;
        //dai
        priceFeeds[
            0xbA7dEebBFC5fA1100Fb055a87773e1E99Cd3507a
        ] = 0x51D7180edA2260cc4F6e4EebB82FEF5c3c2B8300;
        //usdc
        priceFeeds[
            0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E
        ] = 0xF096872672F44d6EBA71458D74fe67F9a77a23B9;

        //sushi
        priceFeeds[
            0x39cf1BD5f15fb22eC3D9Ff86b0727aFc203427cc
        ] = 0x449A373A090d8A1e5F74c63Ef831Ceff39E94563;

        //MIM
        priceFeeds[
            0x130966628846BFd36ff31a822705796e8cb8C18D
        ] = 0x54EdAB30a7134A16a54218AE64C73e1DAf48a8Fb;
        /* //btc
        priceFeeds[
            0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599
        ] = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;
        //usdt
        priceFeeds[
            0xdAC17F958D2ee523a2206206994597C13D831ec7
        ] = 0x3E7d1eAB13ad0104d2750B8863b489D65364e32D;
        //dai
        priceFeeds[
            0x6B175474E89094C44Da98b954EedeAC495271d0F
        ] = 0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9;
        //bnb
        priceFeeds[
            0xB8c77482e45F1F44dE1745F52C74426C631bDD52
        ] = 0x14e613AC84a31f709eadbdF89C6CC390fDc9540A;
        //usdc
        priceFeeds[
            0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
        ] = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4;
        //link
        priceFeeds[
            0x514910771AF9Ca656af840dff83E8264EcF986CA
        ] = 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c;
        //aave
        priceFeeds[
            0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9
        ] = 0x547a514d5e3769680Ce22B2361c10Ea13619e8a9;
        //tusd
        priceFeeds[
            0x0000000000085d4780B73119b644AE5ecd22b376
        ] = 0xec746eCF986E2927Abd291a2A1716c940100f8Ba;
        //mim
        priceFeeds[
            0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3
        ] = 0x7A364e8770418566e3eb2001A96116E6138Eb32F;
        //rai
        priceFeeds[
            0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919
        ] = 0x483d36F6a1d063d580c7a24F9A42B346f3a69fbb;
        //fei
        priceFeeds[
            0x956F47F50A910163D8BF957Cf5846D573E7f87CA
        ] = 0x31e0a88fecB6eC0a411DBe0e9E76391498296EE9;
        //uni
        priceFeeds[
            0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984
        ] = 0x553303d460EE0afB37EdFf9bE42922D8FF63220e;
        //sushi
        priceFeeds[
            0x6B3595068778DD592e39A122f4f5a5cF09C90fE2
        ] = 0xCc70F09A6CC17553b2E31954cD36E4A2d89501f7;
        //xsushi
        priceFeeds[
            0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272
        ] = 0xCC1f5d9e6956447630d703C8e93b2345c2DE3D13;
        //mkr
        priceFeeds[
            0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2
        ] = 0xec1D1B3b0443256cc3860e24a46F108e699484Aa;
        //yfi
        priceFeeds[
            0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e
        ] = 0xA027702dbb89fbd58938e4324ac03B58d812b0E1;
        //comp
        priceFeeds[
            0xc00e94Cb662C3520282E6f5717214004A7f26888
        ] = 0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5;
        //matic
        priceFeeds[
            0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0
        ] = 0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676;
        //1inch
        priceFeeds[
            0x111111111117dC0aa78b770fA6A738034120C302
        ] = 0xc929ad75B72593967DE83E7F7Cda0493458261D9;
        //busd
        priceFeeds[
            0x4Fabb145d64652a948d72533023f6E7A623C7C53
        ] = 0x833D8Eb16D306ed1FbB5D7A2E019e106B960965A;
    */
    }

    /***********
     * Modifiers
     ***********/

    modifier validNameSlug(string memory _slug) {
        bytes memory tmpSlug = bytes(_slug); // Uses memory
        require(tmpSlug.length > 0, "Not valid slug");
        _;
    }
    modifier onlyOwner() {
        require(address(msg.sender) == owner, "!owner");
        _;
    }

    /***********
     * Functions
     ***********/

    /***
     * @notice Allow to set the chainlink feed address of a token
     * This function will be called by owner to add support for new tokens to buy tickets
     * @param _token The address of the ERC20 token to be used to pay for a ticket
     * @param _feed The address of the chainlink feed of the token
     **/
    function setPriceFeed(address _token, address _feed) public onlyOwner {
        priceFeeds[_token] = _feed;
    }

    /***
     * @notice Allow to set refund settings
     * This function will be called by owner to set refunds parameters
     * @param _allow Sets whether self refunds are enabled or not
     * @param _refundFee Percentage of the refunds fee
     * @param _resellFee Percentage of resell fee
     * @param _refundIncFee Amount by which refund fee gets incremented for self refunds
     * @param _refundIncLapse Time lapse between each self refund fee increment for self refunds
     **/
    function setRefund(
        bool _allow,
        uint256 _refundFee,
        uint256 _resellFee,
        uint256 _refundIncFee,
        uint256 _refundIncLapse
    ) public onlyOwner {
        allowSelfRefund = _allow;
        refundFee = _refundFee;
        resellFee = _resellFee;
        refundIncFee = _refundIncFee;
        refundIncLapse = _refundIncLapse;
    }

    /***
     * @notice Allow to enable or disable reselling globally
     * This function will be called by owner to set allowBuyResellable
     * @param _allow Sets whether buying resellable is enabled or not
     **/
    function setResellable(bool _allow) public onlyOwner {
        allowBuyResellable = _allow;
    }

    /***
     * @notice Allow to set tickets
     * This function will be called by owner to set new or update tickets
     * @param _qty Amount of tickets available (eg. 1000 tickets)
     * @param _price Price of ticket in USD (eg 100)
     * @param _endDate Timestamp of date at which tickets won't be available anymore
     * @param _startDate Timestamp of date at which tickets can start being bought
     * @param _slug Name of ticket (eg. early_bird)
     **/
    function setTicket(
        uint256 _qty,
        uint256 _price,
        uint256 _endDate,
        uint256 _startDate,
        string memory slug
    ) public validNameSlug(slug) onlyOwner {
        Ticket memory t;
        t.qty = _qty;
        t.price = _price;
        t.endDate = _endDate;
        t.startDate = _startDate;
        tickets[slug] = t;
    }

    /***
     * @notice Allow to set discounts based on buyer's token balance
     * This function will be called by owner to set token balance based discounts
     * @param _discountToken Address of the token address that will be used (eg. address of $YFI)
     * @param _minAmount Minimum amount of tokens buyer must have to get discount (eg. 1 $YFI)
     * @param _qty How many times can this discount be used (eg. 10 transactions only)
     * @param _amount Amount of the discount in percentage (eg. 5 for a 5% discount)
     * @param _endDate Timestamp of date at which discount won't be available anymore
     * @param _startDate Timestamp of date at which discount can start being used
     * @param _ticketsToAdd Tickets the discount will apply to
     * @param _ticketsToRemove Tickets the discount will not apply to anymore
     **/
    function setTokenDiscount(
        address _discountToken,
        uint256 _minAmount,
        uint256 _qty,
        uint256 _amount,
        uint256 _endDate,
        uint256 _startDate,
        string[] memory ticketsToAdd,
        string[] memory ticketsToRemove
    ) public onlyOwner {
        TokenDiscount memory td;
        td.token = _discountToken;
        td.minAmount = _minAmount;
        td.qty = _qty;
        td.amount = _amount;
        td.endDate = _endDate;
        td.startDate = _startDate;
        tokenDiscounts[_discountToken] = td;

        for (uint256 i = 0; i < ticketsToAdd.length; i++) {
            tokenDiscountTickets[_discountToken][ticketsToAdd[i]] = true;
        }
        for (uint256 i = 0; i < ticketsToRemove.length; i++) {
            tokenDiscountTickets[_discountToken][ticketsToRemove[i]] = false;
        }
    }

    /***
     * @notice Allow to set discounts codes
     * This function will be called by owner to set a discount code
     * @param _code Value of code that can be used
     * @param _qty How many times can this discount be used (eg. 10 transactions only)
     * @param _amount Amount of the discount in percentage (eg. 5 for a 5% discount)
     * @param _endDate Timestamp of date at which discount won't be available anymore
     * @param _startDate Timestamp of date at which discount can start being used
     * @param _ticketsToAdd Tickets the discount will apply to
     * @param _ticketsToRemote Tickets the discount will not apply to anymore
     **/
    function setDiscountCodes(
        string memory _code,
        uint256 _qty,
        uint256 _amount,
        uint256 _endDate,
        uint256 _startDate,
        string[] memory _ticketsToAdd,
        string[] memory _ticketsToRemove
    ) public onlyOwner {
        DiscountCode memory td;
        td.qty = _qty;
        td.amount = _amount;
        td.endDate = _endDate;
        td.startDate = _startDate;
        discountCodes[_code] = td;

        for (uint256 i = 0; i < _ticketsToAdd.length; i++) {
            discountCodeTickets[_code][_ticketsToAdd[i]] = true;
        }
        for (uint256 i = 0; i < _ticketsToRemove.length; i++) {
            discountCodeTickets[_code][_ticketsToRemove[i]] = false;
        }
    }

    /***
     * @notice Allow to set discounts based on buyer address
     * This function will be called by owner to set address based discounts
     * @param _buyer Address of buyer that can use the code
     * @param _qty How many times can this discount be used (eg. 10 transactions only)
     * @param _amount Amount of the discount in percentage (eg. 5 for a 5% discount)
     * @param _endDate Timestamp of date at which discount won't be available anymore
     * @param _startDate Timestamp of date at which discount can start being used
     * @param _ticketsToAdd Tickets the discount will apply to
     * @param _ticketsToRemote Tickets the discount will not apply to anymore
     **/
    function setDiscountAddresses(
        address buyer,
        uint256 qty,
        uint256 amount,
        uint256 endDate,
        uint256 startDate,
        string[] memory ticketsToAdd,
        string[] memory ticketsToRemove
    ) public onlyOwner {
        DiscountAddress memory td;
        td.qty = qty;
        td.amount = amount;
        td.endDate = endDate;
        td.startDate = startDate;
        discountAddresses[buyer] = td;

        for (uint256 i = 0; i < ticketsToAdd.length; i++) {
            discountAddressTickets[buyer][ticketsToAdd[i]] = true;
        }

        for (uint256 i = 0; i < ticketsToRemove.length; i++) {
            discountAddressTickets[buyer][ticketsToRemove[i]] = false;
        }
    }

    /***
     * @notice Buy ticket function
     * This function will be called by tickets buyers to buy tickets
     * @param _buyAttendees mapping of Attendee details
     * @param _buyToken address of token being used to buy tickets (eg DAI, USDC, if ETH use 0x0)
     **/
    function mintTicket(
        Attendee[] memory _buyAttendees,
        address _buyToken
    ) public payable nonReentrant {
        uint256 total = 0;
        uint256 discount = 0;
        //AggregatorV3Interface priceFeed;
        uint256 valueToken = 0;
        require(priceFeeds[_buyToken] != address(0), "token not supported");

        for (uint256 i = 0; i < _buyAttendees.length; i++) {
            require(
                tickets[_buyAttendees[i].ticket].used.current() <
                    tickets[_buyAttendees[i].ticket].qty,
                "sold out"
            );
            require(
                tickets[_buyAttendees[i].ticket].startDate < block.timestamp,
                "not available yet"
            );
            require(
                tickets[_buyAttendees[i].ticket].endDate > block.timestamp,
                "not available anymore"
            );
            discount = getDiscount(msg.sender, _buyAttendees[i]);

            uint256 priceToPay = getPrice(discount, _buyAttendees[i].ticket);
            total += priceToPay;
            _buyAttendees[i].sender = msg.sender;
            _buyAttendees[i].pricePaid = priceToPay;
            _buyAttendees[i].pricePaidInToken = getPriceFromUSD(
                priceToPay,
                _buyToken
            );
            _buyAttendees[i].boughtOn = block.timestamp;
            _buyAttendees[i].buyToken = _buyToken;
            NFTRemote nc = NFTRemote(nftContract);
            uint256 nftId = nc.mintItem(
                msg.sender,
                _buyAttendees[i].ticket,
                _buyAttendees[i].social
            );
            _buyAttendees[i].nftId = nftId;

            setAttendee(
                attendeesCount[msg.sender].current(),
                _buyAttendees[i],
                _buyAttendees[i],
                msg.sender,
                false,
                false
            );
            tickets[_buyAttendees[i].ticket].used.increment();
            attendeesCount[msg.sender].increment();
            emit LMint(msg.sender, _buyAttendees[i], "buy");
        }

        valueToken = getPriceFromUSD(total, _buyToken);

        require(valueToken > 0 || total == 0, "total 0");

        if (_buyToken == address(0)) {
            require(msg.value >= valueToken, "price too low");
            if (msg.value > valueToken) {
                (bool ok, ) = msg.sender.call{value: msg.value - valueToken}(
                    ""
                );
                require(ok, "Failed");
            }
        } else {
            require(
                IERC20(_buyToken).transferFrom(
                    address(msg.sender),
                    address(this),
                    uint256(valueToken)
                ),
                "transfer failed"
            );
        }
        emit LogBuy(msg.sender, msg.value, valueToken, _buyToken);
    }

    /***
     * @notice get pricing in USD for a given token
     * This function gets pricing from chainlink in USD for a token
     * @param _priceUSD amount in USD
     * @param _token token address
     **/
    function getPriceFromUSD(
        uint256 _priceUSD,
        address _token
    ) private view returns (uint256) {
        AggregatorV3Interface priceFeed;
        priceFeed = AggregatorV3Interface(priceFeeds[_token]);
        (, int256 latestPrice, , , ) = priceFeed.latestRoundData();
        //int256 latestPrice = 326393000000;
        uint256 decimals = 18;
        if (_token != 0x0000000000000000000000000000000000000000) {
            IERC20Metadata ercToken = IERC20Metadata(_token);
            decimals = ercToken.decimals();
        }
        uint256 price = uint256(
            (int256(_priceUSD) * int256(10 ** decimals)) / latestPrice
        );
        return price;
    }

    /***
     * @notice get price minus discount
     * This function caluculates price minus discount
     * @param _discount discount amount
     * @param _ticket ticket slug name
     **/
    function getPrice(
        uint256 _discount,
        string memory _ticket
    ) public view returns (uint256) {
        uint256 price = tickets[_ticket].price;
        return price - (price * _discount) / 100;
    }

    /***
     * @notice retrieve attendee details
     * This function gets Attendee details by address and index
     * @param _sender Address of attendee
     * @param _index Attendee ticket index (each attendee can have more than one ticket)
     **/
    function getAttendee(
        address _sender,
        uint256 _index
    ) private view returns (Attendee memory attendee) {
        SRTicketsDiscountsRemote dc = SRTicketsDiscountsRemote(
            discountContract
        );
        attendee = dc.getAttendee(_sender, _index);
    }

    /***
     * @notice set attendee details
     * This function sets Attendee details by address and index
     * @param _attendeeIndex index of attendee
     * @param _newAttendee new attendee struct
     * @param _attendee current attendee struct
     * @param _sender Address of attendee
     * @param _resell true if this operation is a resell of the attendee's ticket
     * @param _isRefund true if this operation is a refund of the attendee's ticket
     **/
    function setAttendee(
        uint256 _attendeeIndex,
        Attendee memory _newAttendee,
        Attendee memory _attendee,
        address _sender,
        bool _resell,
        bool _isRefund
    ) private {
        SRTicketsDiscountsRemote dc = SRTicketsDiscountsRemote(
            discountContract
        );
        dc.setAttendee(
            _attendeeIndex,
            _newAttendee,
            _attendee,
            _sender,
            _resell,
            _isRefund
        );
    }

    /***
     * @notice get discount for an attendee
     * This view function checks if an attendee gets a discount
     * @param _sender Address of attendee
     * @param _attendee current attendee struct
     **/
    function getDiscountView(
        address _sender,
        Attendee memory _attendee
    ) public view returns (uint256) {
        SRTicketsDiscountsRemote.DiscountResponse memory dr = getDiscountAmount(
            _sender,
            _attendee
        );
        return dr.discountAmount; //discountCodeTickets["50pc-discount"]["conference-only"];
    }

    /***
     * @notice get discount for all attendees
     * This view function checks if each attendee gets a discount
     * @param _sender Address of buyer
     * @param _attendees attendees array
     **/
    function getDiscountsView(
        address _sender,
        Attendee[] memory _attendees
    ) public view returns (uint256) {
        uint256 total = 0;
        for (uint256 i = 0; i < _attendees.length; i++) {
            SRTicketsDiscountsRemote.DiscountResponse
                memory dr = getDiscountAmount(_sender, _attendees[i]);
            total = total + dr.discountAmount; //discountCodeTickets["50pc-discount"]["conference-only"];
        }
        return total;
    }

    /***
     * @notice get discount amount for an attendee
     * This function checks if an attendee gets a discount and apllies it if true
     * @param _sender Address of attendee
     * @param _attendee current attendee struct
     **/
    function getDiscount(
        address _sender,
        Attendee memory _attendee
    ) private returns (uint256) {
        SRTicketsDiscountsRemote.DiscountResponse memory dr = getDiscountAmount(
            _sender,
            _attendee
        );
        if (dr.hasDiscountCode) {
            discountCodes[_attendee.discountCode].used.increment();
        }
        if (dr.hasDiscountAddress) {
            discountAddresses[_sender].used.increment();
        }
        if (dr.hasTokenDiscount) {
            tokenDiscounts[_attendee.tokenDiscount].used.increment();
            tokenDiscountBuyer[_attendee.tokenDiscount][_sender] = true;
        }
        return dr.discountAmount;
    }

    /***
     * @notice get discount amount for an attendee
     * This function computes discount amount for an attendee if any
     * @param _sender Address of attendee
     * @param _attendee current attendee struct
     **/
    function getDiscountAmount(
        address _sender,
        Attendee memory _attendee
    ) private view returns (SRTicketsDiscountsRemote.DiscountResponse memory) {
        //check sender Discount code
        SRTicketsDiscountsRemote dc = SRTicketsDiscountsRemote(
            discountContract
        );
        SRTicketsDiscountsRemote.SenderAndTokenDiscountBuyer memory stdb;
        stdb.sender = _sender;
        stdb.tokenDiscountBuyer = tokenDiscountBuyer[_attendee.tokenDiscount][
            _sender
        ];
        SRTicketsDiscountsRemote.DiscountResponse memory dr = dc
            .getDiscountView(
                stdb,
                discountCodeTickets[_attendee.discountCode][_attendee.ticket],
                discountCodes[_attendee.discountCode],
                discountAddressTickets[_attendee.sender][_attendee.ticket],
                discountAddresses[_attendee.sender],
                tokenDiscountTickets[_attendee.tokenDiscount][_attendee.ticket],
                tokenDiscounts[_attendee.tokenDiscount],
                _attendee.tokenDiscount
            );
        return dr;
    }

    /***
     * @notice update attendee details
     * This function allows an attendee to update their own ticket
     * if new ticket is more expensive, attendee needs to pay the difference
     * @param _attendeeIndex attendee index
     * @param _newAttendee new attendee details
     **/
    function updateAttendee(
        uint256 _attendeeIndex,
        address _attendeeAddress,
        Attendee memory _newAttendee
    ) public payable nonReentrant {
        Attendee memory oldAttendee = getAttendee(
            _attendeeAddress,
            _attendeeIndex
        );

        require(
            oldAttendee.sender == msg.sender || msg.sender == owner,
            "not allowed to update"
        );
        require(!oldAttendee.cancelled, "already cancelled");

        //if attendee is just updating eg. their name but same ticket, skip even if ticket has gone up in price
        if (
            (oldAttendee.sender == msg.sender || msg.sender == owner) &&
            !stringsEquals(_newAttendee.ticket, oldAttendee.ticket)
        ) {
            require(
                tickets[_newAttendee.ticket].used.current() <
                    tickets[_newAttendee.ticket].qty,
                "sold out"
            );
            require(
                tickets[_newAttendee.ticket].startDate < block.timestamp,
                "not available yet"
            );
            require(
                tickets[_newAttendee.ticket].endDate > block.timestamp,
                "not available anymore"
            );
            //only charge more if attendee is updating to a different more expensive ticket
            if (tickets[_newAttendee.ticket].price > oldAttendee.pricePaid) {
                uint256 newAmountPaidInToken = getPriceFromUSD(
                    tickets[_newAttendee.ticket].price - oldAttendee.pricePaid,
                    oldAttendee.buyToken
                );
                if (oldAttendee.buyToken == address(0)) {
                    require(
                        msg.value >= newAmountPaidInToken,
                        "new ticket more expensive"
                    );
                } else {
                    require(
                        IERC20(oldAttendee.buyToken).transferFrom(
                            address(msg.sender),
                            address(this),
                            newAmountPaidInToken
                        ),
                        "transfer failed"
                    );
                }
                //increase number of tickets used with this update
                tickets[_newAttendee.ticket].used.increment();
                //decrease number of tickets used for attendee ticket pre-update
                tickets[oldAttendee.ticket].used.decrement();
                oldAttendee.pricePaid = tickets[_newAttendee.ticket].price;
                oldAttendee.pricePaidInToken =
                    oldAttendee.pricePaidInToken +
                    newAmountPaidInToken;
            }
        }
        setAttendee(
            _attendeeIndex,
            _newAttendee,
            oldAttendee,
            _attendeeAddress,
            false,
            false
        );
    }

    /***
     * @notice refund attendee
     * This function allows owner to refund attendee
     * @param _buyer buyer's address
     * @param _attendeeIndex attendee index
     * @param _amount amount to refund
     **/
    function refund(
        address _buyer,
        uint256 _attendeeIndex,
        uint256 _amount
    ) public onlyOwner nonReentrant {
        Attendee memory attendee = getAttendee(_buyer, _attendeeIndex);
        require(
            attendee.pricePaidInToken >= _amount,
            "refund higher than paid price"
        );
        require(!attendee.cancelled, "already cancelled");
        //set attendee nft as cancelled
        NFTRemote nc = NFTRemote(nftContract);
        nc.setCancelled(attendee.nftId);
        tickets[attendee.ticket].used.decrement();

        if (attendee.buyToken != address(0)) {
            IERC20(attendee.buyToken).safeTransfer(
                address(attendee.sender),
                _amount
            );
            attendee.refunded = _amount;
            attendee.cancelled = true;
            setAttendee(
                _attendeeIndex,
                attendee,
                attendee,
                attendee.sender,
                false,
                true
            );
        } else {
            (bool ok, ) = address(_buyer).call{value: _amount}("");
            require(ok, "Failed");
            attendee.refunded = _amount;
            attendee.cancelled = true;
            setAttendee(
                _attendeeIndex,
                attendee,
                attendee,
                attendee.sender,
                false,
                true
            );
        }
        emit LogRefund(_buyer, _amount, _attendeeIndex, attendee.buyToken);
    }

    /***
     * @notice self-refund attendee
     * This function allows attendee to get a refund automatically
     * as time passes by, every x seconds the refundable amount decreases by y
     *  x is refundIncLapse and y refundIncFee
     * @param _attendeeIndex attendee index
     **/
    function selfRefund(uint256 _attendeeIndex) public nonReentrant {
        Attendee memory attendee = getAttendee(msg.sender, _attendeeIndex);
        require(attendee.sender == msg.sender, "sender is not buyer");
        require(allowSelfRefund, "refund not possible");
        require(!attendee.cancelled, "already cancelled");
        require(!attendee.resold, "resold, see refund with reseller");
        require(
            tickets[attendee.ticket].endDate > block.timestamp,
            "refund not possible anymore"
        );
        uint256 feePercentage = (refundIncFee *
            (block.timestamp - attendee.boughtOn)) / refundIncLapse;
        require(feePercentage < 100, "refund not possible");

        uint256 amount = attendee.pricePaidInToken -
            ((feePercentage * attendee.pricePaidInToken) / 100);
        //set attendee nft as cancelled
        NFTRemote nc = NFTRemote(nftContract);
        nc.setCancelled(attendee.nftId);
        tickets[attendee.ticket].used.decrement();
        if (attendee.buyToken != address(0)) {
            IERC20(attendee.buyToken).safeTransfer(
                address(attendee.sender),
                amount
            );
            attendee.refunded = amount;
            attendee.cancelled = true;
            setAttendee(
                _attendeeIndex,
                attendee,
                attendee,
                attendee.sender,
                false,
                true
            );
        } else {
            (bool ok, ) = address(attendee.sender).call{value: amount}("");
            require(ok, "Failed");
            attendee.refunded = amount;
            attendee.cancelled = true;
            setAttendee(
                _attendeeIndex,
                attendee,
                attendee,
                attendee.sender,
                false,
                true
            );
        }
    }

    /***
     * @notice buy a resellable ticket
     * This function allows anyone to buy someone's else ticket as long as allowResell is true
     * @param _attendeeIndex attendee index
     * @param _newAttendee newAttendee details
     **/
    function buyResellable(
        uint256 _attendeeIndex,
        Attendee memory _newAttendee
    ) public payable nonReentrant {
        Attendee memory attendee = getAttendee(
            _newAttendee.sender,
            _attendeeIndex
        );
        bool canUpdate = false;
        require(attendee.allowResell, "not for sell");
        require(allowBuyResellable, "reselling desabled");
        require(!attendee.cancelled, "already cancelled");
        require(
            stringsEquals(_newAttendee.ticket, attendee.ticket),
            "different ticket"
        );
        if (attendee.buyToken != address(0)) {
            require(
                IERC20(attendee.buyToken).transferFrom(
                    address(msg.sender),
                    address(this),
                    uint256((attendee.resellPrice * resellFee) / 100)
                ),
                "transfer failed"
            );
            require(
                IERC20(attendee.buyToken).transferFrom(
                    address(msg.sender),
                    address(attendee.sender),
                    uint256(
                        attendee.resellPrice -
                            (attendee.resellPrice * resellFee) /
                            100
                    )
                ),
                "transfer failed"
            );
            canUpdate = true;
        } else {
            require(msg.value == attendee.resellPrice, "not enough fund");
            (bool ok, ) = attendee.sender.call{
                value: attendee.resellPrice -
                    (attendee.resellPrice * resellFee) /
                    100
            }("");
            require(ok, "Failed");
            canUpdate = true;
        }
        if (canUpdate) {
            setAttendee(
                attendeesCount[msg.sender].current(),
                _newAttendee,
                attendee,
                msg.sender,
                true,
                false
            );

            attendeesCount[msg.sender].increment();
        }
    }

    /***
     * @notice withdraw funds
     * This function allows owner to withdraw funds from contracts
     * @param _token address of token to withdraw
     * @param _amount amount to withdraw
     **/
    function withdraw(address _token, uint256 _amount) external onlyOwner {
        if (_token != address(0)) {
            IERC20(_token).safeTransfer(address(owner), _amount);
        } else {
            (bool ok, ) = owner.call{value: _amount}("");
            require(ok, "Failed");
        }
    }

    function setOwner(address _newOwner) public onlyOwner {
        tbcOwner = _newOwner;
        emit LogSetOwner(msg.sender, _newOwner);
    }

    function confirmOwner(address _newOwner) public onlyOwner {
        require(_newOwner == tbcOwner, "not confirmed");
        require(
            _newOwner != 0x0000000000000000000000000000000000000000,
            "address cant be 0"
        );
        owner = _newOwner;
    }

    /*    function getThing() public view returns (uint256) {
        //        return discountAddressTickets[attendee.sender][attendee.ticket];
        //return discountAddresses[0x70997970C51812dc3A010C7d01b50e0d17dc79C8];
        AggregatorV3Interface priceFeed;
        priceFeed = AggregatorV3Interface(
            priceFeeds[0x0000000000000000000000000000000000000000]
        );
        (, int256 latestPrice, , , ) = priceFeed.latestRoundData();
        //int256 latestPrice = 326393000000;
        //uint256 price = uint256((int256(100 * 10**8) * 10**18) / latestPrice);

        return uint256(latestPrice);
    }
   */
}

function stringsEquals(string memory s1, string memory s2) pure returns (bool) {
    bytes memory b1 = bytes(s1);
    bytes memory b2 = bytes(s2);
    uint256 l1 = b1.length;
    if (l1 != b2.length) return false;
    for (uint256 i = 0; i < l1; i++) {
        if (b1[i] != b2[i]) return false;
    }
    return true;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @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(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the 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}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (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.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @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.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, _allowances[owner][spender] + addedValue);
        return true;
    }

    /**
     * @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`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = _allowances[owner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * 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(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @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) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @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) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @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
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Spend `amount` form the allowance of `owner` toward `spender`.
     *
     * 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
    ) internal virtual {
        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(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @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(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

pragma solidity ^0.8.15;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract TestToken is ERC20 {
    constructor() ERC20("TestToken", "TT") {
        mintTokens();
    }

    function mintTokens() public {
        _mint(msg.sender, 100000000000000000000000);
    }

    function mintTokensTo(address beneficiary) public {
        _mint(beneficiary, 100000000000000000000000);
    }
}

Please enter a contract address above to load the contract details and source code.

Context size (optional):