contract Factory is ContextUpgradeSafe, Configurable, Constants {
    using SafeERC20 for IERC20;
    using SafeMath for uint;

    bytes32 public constant REGISTER_TYPEHASH   = keccak256("RegisterMapping(uint mainChainId,address token,uint[] chainIds,address[] mappingTokenMappeds,address signatory)");
    bytes32 public constant CREATE_TYPEHASH     = keccak256("CreateMappingToken(address creator,uint mainChainId,address token,string name,string symbol,uint8 decimals,uint cap,address signatory)");
    bytes32 public constant DOMAIN_TYPEHASH     = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
    bytes32 public DOMAIN_SEPARATOR;

    mapping (bytes32 => address) public productImplementations;
    mapping (address => address) public tokenMappeds;                // token => tokenMapped
    mapping (address => address) public mappableTokens;              // creator => mappableTokens
    mapping (uint256 => mapping (address => address)) public mappingTokens;     // mainChainId => token or creator => mappableTokens
    mapping (address => bool) public authorties;
    
    // only on ethereum mainnet
    mapping (address => uint) public authCountOf;                   // signatory => count
    mapping (address => uint256) internal _mainChainIdTokens;       // mappingToken => mainChainId+token
    mapping (address => mapping (uint => address)) public mappingTokenMappeds;  // token => chainId => mappingToken or tokenMapped
    uint[] public supportChainIds;
    mapping (string  => uint256) internal _certifiedTokens;         // symbol => mainChainId+token
    string[] public certifiedSymbols;

    function __MappingTokenFactory_init(address _governor, address _implTokenMapped, address _implMappableToken, address _implMappingToken, address _feeTo) external initializer {
        __Governable_init_unchained(_governor);
        __MappingTokenFactory_init_unchained(_implTokenMapped, _implMappableToken, _implMappingToken, _feeTo);
    }
    
    function __MappingTokenFactory_init_unchained(address _implTokenMapped, address _implMappableToken, address _implMappingToken, address _feeTo) public governance {
        config[_fee_]                           = 0.005 ether;
        //config[_feeCreate_]                     = 0.200 ether;
        config[_feeTo_]                         = uint(_feeTo);
        config[_minSignatures_]                 = 3;
        config[_uniswapRounter_]                = uint(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

        DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes('MappingTokenFactory')), _chainId(), address(this)));
        upgradeProductImplementationsTo_(_implTokenMapped, _implMappableToken, _implMappingToken);
        emit ProductProxyCodeHash(keccak256(type(InitializableProductProxy).creationCode));
    }
    event ProductProxyCodeHash(bytes32 codeHash);

    function upgradeProductImplementationsTo_(address _implTokenMapped, address _implMappableToken, address _implMappingToken) public governance {
        productImplementations[_TokenMapped_]   = _implTokenMapped;
        productImplementations[_MappableToken_] = _implMappableToken;
        productImplementations[_MappingToken_]  = _implMappingToken;
    }
    
    function setAuthorty_(address authorty, bool enable) virtual external governance {
        authorties[authorty] = enable;
        emit SetAuthorty(authorty, enable);
    }
    event SetAuthorty(address indexed authorty, bool indexed enable);
    
    modifier onlyAuthorty {
        require(authorties[_msgSender()], 'only authorty');
        _;
    }
    
    function increaseAuthQuotas(address mappingTokenMapped, address[] memory signatorys, uint[] memory increments) virtual external onlyAuthorty returns (uint[] memory quotas) {
        quotas = MappingBase(mappingTokenMapped).increaseAuthQuotas(signatorys, increments);
        for(uint i=0; i<signatorys.length; i++)
            emit IncreaseAuthQuota(_msgSender(), mappingTokenMapped, signatorys[i], increments[i], quotas[i]);
    }
    
    function increaseAuthQuota(address mappingTokenMapped, address signatory, uint increment) virtual external onlyAuthorty returns (uint quota) {
        quota = MappingBase(mappingTokenMapped).increaseAuthQuota(signatory, increment);
        emit IncreaseAuthQuota(_msgSender(), mappingTokenMapped, signatory, increment, quota);
    }
    event IncreaseAuthQuota(address indexed authorty, address indexed mappingTokenMapped, address indexed signatory, uint increment, uint quota);
    
    function decreaseAuthQuotas(address mappingTokenMapped, address[] memory signatorys, uint[] memory decrements) virtual external onlyAuthorty returns (uint[] memory quotas) {
        quotas = MappingBase(mappingTokenMapped).decreaseAuthQuotas(signatorys, decrements);
        for(uint i=0; i<signatorys.length; i++)
            emit DecreaseAuthQuota(_msgSender(), mappingTokenMapped, signatorys[i], decrements[i], quotas[i]);
    }
    
    function decreaseAuthQuota(address mappingTokenMapped, address signatory, uint decrement) virtual external onlyAuthorty returns (uint quota) {
        quota = MappingBase(mappingTokenMapped).decreaseAuthQuota(signatory, decrement);
        emit DecreaseAuthQuota(_msgSender(), mappingTokenMapped, signatory, decrement, quota);
    }
    event DecreaseAuthQuota(address indexed authorty, address indexed mappingTokenMapped, address indexed signatory, uint decrement, uint quota);

    function increaseAuthCount(address[] memory signatorys, uint[] memory increments) virtual external returns (uint[] memory counts) {
        require(signatorys.length == increments.length, 'two array lenth not equal');
        counts = new uint[](signatorys.length);
        for(uint i=0; i<signatorys.length; i++)
            counts[i] = increaseAuthCount(signatorys[i], increments[i]);
    }
    
    function increaseAuthCount(address signatory, uint increment) virtual public onlyAuthorty returns (uint count) {
        count = authCountOf[signatory].add(increment);
        authCountOf[signatory] = count;
        emit IncreaseAuthQuota(_msgSender(), signatory, increment, count);
    }
    event IncreaseAuthQuota(address indexed authorty, address indexed signatory, uint increment, uint quota);
    
    function decreaseAuthCounts(address[] memory signatorys, uint[] memory decrements) virtual external returns (uint[] memory counts) {
        require(signatorys.length == decrements.length, 'two array lenth not equal');
        counts = new uint[](signatorys.length);
        for(uint i=0; i<signatorys.length; i++)
            counts[i] = decreaseAuthCount(signatorys[i], decrements[i]);
    }
    
    function decreaseAuthCount(address signatory, uint decrement) virtual public onlyAuthorty returns (uint count) {
        count = authCountOf[signatory];
        if(count < decrement)
            decrement = count;
        return _decreaseAuthCount(signatory, decrement);
    }
    
    function _decreaseAuthCount(address signatory, uint decrement) virtual internal returns (uint count) {
        count = authCountOf[signatory].sub(decrement);
        authCountOf[signatory] = count;
        emit DecreaseAuthCount(_msgSender(), signatory, decrement, count);
    }
    event DecreaseAuthCount(address indexed authorty, address indexed signatory, uint decrement, uint count);

    function supportChainCount() public view returns (uint) {
        return supportChainIds.length;
    }
    
    function mainChainIdTokens(address mappingToken) virtual public view returns(uint mainChainId, address token) {
        uint256 chainIdToken = _mainChainIdTokens[mappingToken];
        mainChainId = chainIdToken >> 160;
        token = address(chainIdToken);
    }
    
    function chainIdMappingTokenMappeds(address tokenOrMappingToken) virtual external view returns (uint[] memory chainIds, address[] memory mappingTokenMappeds_) {
        (, address token) = mainChainIdTokens(tokenOrMappingToken);
        if(token == address(0))
            token = tokenOrMappingToken;
        uint N = 0;
        for(uint i=0; i<supportChainCount(); i++)
            if(mappingTokenMappeds[token][supportChainIds[i]] != address(0))
                N++;
        chainIds = new uint[](N);
        mappingTokenMappeds_ = new address[](N);
        uint j = 0;
        for(uint i=0; i<supportChainCount(); i++) {
            uint chainId = supportChainIds[i];
            address mappingTokenMapped = mappingTokenMappeds[token][chainId];
            if(mappingTokenMapped != address(0)) {
                chainIds[j] = chainId;
                mappingTokenMappeds_[j] = mappingTokenMapped;
                j++;
            }
        }
    }
    
    function isSupportChainId(uint chainId) virtual public view returns (bool) {
        for(uint i=0; i<supportChainCount(); i++)
            if(supportChainIds[i] == chainId)
                return true;
        return false;
    }
    
    function registerSupportChainId_(uint chainId_) virtual external governance {
        require(_chainId() == 1 || _chainId() == 3, 'called only on ethereum mainnet');
        require(!isSupportChainId(chainId_), 'support chainId already');
        supportChainIds.push(chainId_);
    }
    
    function _registerMapping(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_) virtual internal {
        require(_chainId() == 1 || _chainId() == 3, 'called only on ethereum mainnet');
        require(chainIds.length == mappingTokenMappeds_.length, 'two array lenth not equal');
        require(isSupportChainId(mainChainId), 'Not support mainChainId');
        for(uint i=0; i<chainIds.length; i++) {
            require(isSupportChainId(chainIds[i]), 'Not support chainId');
            //require(_mainChainIdTokens[mappingTokenMappeds_[i]] == 0 || _mainChainIdTokens[mappingTokenMappeds_[i]] == (mainChainId << 160) | uint(token), 'mainChainIdTokens exist already');
            //require(mappingTokenMappeds[token][chainIds[i]] == address(0), 'mappingTokenMappeds exist already');
            //if(_mainChainIdTokens[mappingTokenMappeds_[i]] == 0)
                _mainChainIdTokens[mappingTokenMappeds_[i]] = (mainChainId << 160) | uint(token);
            mappingTokenMappeds[token][chainIds[i]] = mappingTokenMappeds_[i];
            emit RegisterMapping(mainChainId, token, chainIds[i], mappingTokenMappeds_[i]);
        }
    }
    event RegisterMapping(uint mainChainId, address token, uint chainId, address mappingTokenMapped);
    
    function registerMapping_(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_) virtual external governance {
        _registerMapping(mainChainId, token, chainIds, mappingTokenMappeds_);
    }
    
    function registerMapping(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_, Signature[] memory signatures) virtual external payable {
        _chargeFee();
        uint N = signatures.length;
        require(N >= getConfig(_minSignatures_), 'too few signatures');
        for(uint i=0; i<N; i++) {
            for(uint j=0; j<i; j++)
                require(signatures[i].signatory != signatures[j].signatory, 'repetitive signatory');
            bytes32 structHash = keccak256(abi.encode(REGISTER_TYPEHASH, mainChainId, token, keccak256(abi.encodePacked(chainIds)), keccak256(abi.encodePacked(mappingTokenMappeds_)), signatures[i].signatory));
            bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
            address signatory = ecrecover(digest, signatures[i].v, signatures[i].r, signatures[i].s);
            require(signatory != address(0), "invalid signature");
            require(signatory == signatures[i].signatory, "unauthorized");
            _decreaseAuthCount(signatures[i].signatory, 1);
            emit AuthorizeRegister(mainChainId, token, signatory);
        }
        _registerMapping(mainChainId, token, chainIds, mappingTokenMappeds_);
    }
    event AuthorizeRegister(uint indexed mainChainId, address indexed token, address indexed signatory);

    function certifiedCount() external view returns (uint) {
        return certifiedSymbols.length;
    }
    
    function certifiedTokens(string memory symbol) public view returns (uint mainChainId, address token) {
        uint256 chainIdToken = _certifiedTokens[symbol];
        mainChainId = chainIdToken >> 160;
        token = address(chainIdToken);
    }
    
    function allCertifiedTokens() external view returns (string[] memory symbols, uint[] memory chainIds, address[] memory tokens) {
        symbols = certifiedSymbols;
        uint N = certifiedSymbols.length;
        chainIds = new uint[](N);
        tokens = new address[](N);
        for(uint i=0; i<N; i++)
            (chainIds[i], tokens[i]) = certifiedTokens(certifiedSymbols[i]);
    }

    function registerCertified_(string memory symbol, uint mainChainId, address token) external governance {
        require(_chainId() == 1 || _chainId() == 3, 'called only on ethereum mainnet');
        require(isSupportChainId(mainChainId), 'Not support mainChainId');
        require(_certifiedTokens[symbol] == 0, 'Certified added already');
        if(mainChainId == _chainId())
            require(keccak256(bytes(symbol)) == keccak256(bytes(ERC20UpgradeSafe(token).symbol())), 'symbol different');
        _certifiedTokens[symbol] = (mainChainId << 160) | uint(token);
        certifiedSymbols.push(symbol);
        emit RegisterCertified(symbol, mainChainId, token);
    }
    event RegisterCertified(string indexed symbol, uint indexed mainChainId, address indexed token);
    
    function updateCertified_(string memory symbol, uint mainChainId, address token) external governance {
        require(_chainId() == 1 || _chainId() == 3, 'called only on ethereum mainnet');
        require(isSupportChainId(mainChainId), 'Not support mainChainId');
        //require(_certifiedTokens[symbol] == 0, 'Certified added already');
        if(mainChainId == _chainId())
            require(keccak256(bytes(symbol)) == keccak256(bytes(ERC20UpgradeSafe(token).symbol())), 'symbol different');
        _certifiedTokens[symbol] = (mainChainId << 160) | uint(token);
        //certifiedSymbols.push(symbol);
        emit UpdateCertified(symbol, mainChainId, token);
    }
    event UpdateCertified(string indexed symbol, uint indexed mainChainId, address indexed token);
    
    // calculates the CREATE2 address for a pair without making any external calls
    function calcMapping(uint mainChainId, address tokenOrCreator) public view returns (address) {
        return address(uint(keccak256(abi.encodePacked(
                hex'ff',
                address(this),
                keccak256(abi.encodePacked(mainChainId, tokenOrCreator)),
				keccak256(type(InitializableProductProxy).creationCode)                    //hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
            ))));
    }

    function createTokenMapped(address token) external payable returns (address tokenMapped) {
        _chargeFee();
        IERC20(token).totalSupply();                                                            // just for check
        require(tokenMappeds[token] == address(0), 'TokenMapped created already');

        bytes32 salt = keccak256(abi.encodePacked(_chainId(), token));

        bytes memory bytecode = type(InitializableProductProxy).creationCode;
        assembly {
            tokenMapped := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        InitializableProductProxy(payable(tokenMapped)).__InitializableProductProxy_init(address(this), _TokenMapped_, abi.encodeWithSignature('__TokenMapped_init(address,address)', address(this), token));
        
        tokenMappeds[token] = tokenMapped;
        emit CreateTokenMapped(_msgSender(), token, tokenMapped);
    }
    event CreateTokenMapped(address indexed creator, address indexed token, address indexed tokenMapped);
    
    function createMappableToken(string memory name, string memory symbol, uint8 decimals, uint totalSupply) external payable returns (address mappableToken) {
        _chargeFee();
        require(mappableTokens[_msgSender()] == address(0), 'MappableToken created already');

        bytes32 salt = keccak256(abi.encodePacked(_chainId(), _msgSender()));

        bytes memory bytecode = type(InitializableProductProxy).creationCode;
        assembly {
            mappableToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        InitializableProductProxy(payable(mappableToken)).__InitializableProductProxy_init(address(this), _MappableToken_, abi.encodeWithSignature('__MappableToken_init(address,address,string,string,uint8,uint256)', address(this), _msgSender(), name, symbol, decimals, totalSupply));
        
        mappableTokens[_msgSender()] = mappableToken;
        emit CreateMappableToken(_msgSender(), name, symbol, decimals, totalSupply, mappableToken);
    }
    event CreateMappableToken(address indexed creator, string name, string symbol, uint8 decimals, uint totalSupply, address indexed mappableToken);
    
    function _createMappingToken(uint mainChainId, address token, address creator, string memory name, string memory symbol, uint8 decimals, uint cap) internal returns (address mappingToken) {
        _chargeFee();
        address tokenOrCreator = (token == address(0)) ? creator : token;
        require(mappingTokens[mainChainId][tokenOrCreator] == address(0), 'MappingToken created already');

        bytes32 salt = keccak256(abi.encodePacked(mainChainId, tokenOrCreator));

        bytes memory bytecode = type(InitializableProductProxy).creationCode;
        assembly {
            mappingToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        InitializableProductProxy(payable(mappingToken)).__InitializableProductProxy_init(address(this), _MappingToken_, abi.encodeWithSignature('__MappingToken_init(address,uint256,address,address,string,string,uint8,uint256)', address(this), mainChainId, token, creator, name, symbol, decimals, cap));
        
        mappingTokens[mainChainId][tokenOrCreator] = mappingToken;
        emit CreateMappingToken(mainChainId, token, creator, name, symbol, decimals, cap, mappingToken);
    }
    event CreateMappingToken(uint mainChainId, address indexed token, address indexed creator, string name, string symbol, uint8 decimals, uint cap, address indexed mappingToken);
    
    function createMappingToken_(uint mainChainId, address token, address creator, string memory name, string memory symbol, uint8 decimals, uint cap) public payable governance returns (address mappingToken) {
        return _createMappingToken(mainChainId, token, creator, name, symbol, decimals, cap);
    }
    
    function createMappingToken(uint mainChainId, address token, string memory name, string memory symbol, uint8 decimals, uint cap, Signature[] memory signatures) public payable returns (address mappingToken) {
        uint N = signatures.length;
        require(N >= getConfig(_minSignatures_), 'too few signatures');
        for(uint i=0; i<N; i++) {
            for(uint j=0; j<i; j++)
                require(signatures[i].signatory != signatures[j].signatory, 'repetitive signatory');
            bytes32 hash = keccak256(abi.encode(CREATE_TYPEHASH, _msgSender(), mainChainId, token, keccak256(bytes(name)), keccak256(bytes(symbol)), decimals, cap, signatures[i].signatory));
            hash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash));
            address signatory = ecrecover(hash, signatures[i].v, signatures[i].r, signatures[i].s);
            require(signatory != address(0), "invalid signature");
            require(signatory == signatures[i].signatory, "unauthorized");
            _decreaseAuthCount(signatures[i].signatory, 1);
            emit AuthorizeCreate(mainChainId, token, _msgSender(), name, symbol, decimals, cap, signatory);
        }
        return _createMappingToken(mainChainId, token, _msgSender(), name, symbol, decimals, cap);
    }
    event AuthorizeCreate(uint mainChainId, address indexed token, address indexed creator, string name, string symbol, uint8 decimals, uint cap, address indexed signatory);
    
    function _chargeFee() virtual internal {
        require(msg.value >= Math.min(config[_feeCreate_], 1 ether), 'fee for Create is too low');
        address payable feeTo = address(config[_feeTo_]);
        if(feeTo == address(0))
            feeTo = address(uint160(address(this)));
        feeTo.transfer(msg.value);
        emit ChargeFee(_msgSender(), feeTo, msg.value);
    }
    event ChargeFee(address indexed from, address indexed to, uint value);

    uint256[50] private __gap;
}
function calcMapping(uint mainChainId, address tokenOrCreator) public view returns (address) {
        return address(uint(keccak256(abi.encodePacked(
                hex'ff',
                address(this),
                keccak256(abi.encodePacked(mainChainId, tokenOrCreator)),
				keccak256(type(InitializableProductProxy).creationCode)                    //hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
            ))));
    }
// calculates the CREATE2 address for a pair without making any external calls