// Contract: BonesClubHeritageBridge
// Target function: function addReceived1155(address _address, uint256 _tokenId) external onlyOwner
 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);
            }
        }
    }
}

// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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;
}


// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
/**
 * @dev These functions deal with verification of Merkle Trees proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];
            if (computedHash <= proofElement) {
                // Hash(current computed hash + current element of the proof)
                computedHash = _efficientHash(computedHash, proofElement);
            } else {
                // Hash(current element of the proof + current computed hash)
                computedHash = _efficientHash(proofElement, computedHash);
            }
        }
        return computedHash;
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

abstract contract BonesHeritageI is Ownable, IERC721 {
    function migrate(address _owner, uint256 _tokenId) external virtual;

    function exists(uint256 _tokenId) external view virtual returns (bool);

    function getMaxSupply() external virtual returns (uint256);

    function tokensOfOwner(address _owner) external view virtual returns (uint256[] memory);
}


/**
 * @dev BonesClubHeritageBridge contract for bridging shared OS 1155 into a custom 721 contract
 */
contract BonesClubHeritageBridge is ERC1155Holder, Ownable, ReentrancyGuard {
    using Strings for uint256;
    using Strings for uint16;
    
    uint32 public totalBridged;

    bytes32 public merkleRoot;

    uint256[] public idsReceived;
    uint16[] public idsBridged;

    bool public bridgingEnabled;

    mapping(uint256 => address) public idsAndSenders;
    mapping(address => uint256[]) public sendersAndIds;

    mapping(address => uint256[]) public oldsIdsBridgedBySender;

    IERC1155 public osContract;
    BonesHeritageI public bonesContract;

    event ReceivedFromOS(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId, uint256 _amount);

    event ReceivedFrom721(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId);

    event Minted721(address indexed _sender, uint256 indexed _tokenId);

    event ToggleBridging(bool _enabled);

    event Transferred1155(address indexed _to, uint256 indexed _tokenId);

    constructor() {
        bridgingEnabled = true;
    }

    function onERC1155Received(
        address _sender,
        address _receiver,
        uint256 _tokenId,
        uint256 _amount,
        bytes memory _data
    ) public override nonReentrant returns (bytes4) {
        require(msg.sender == address(osContract), "Forbidden");
        require(bridgingEnabled, "Bridging is stopped");

        triggerReceived1155(_receiver, _tokenId);

        emit ReceivedFromOS(msg.sender, _receiver, _tokenId, _amount);
        return super.onERC1155Received(_sender, _receiver, _tokenId, _amount, _data);
    }

    function onERC1155BatchReceived(
        address _sender,
        address _receiver,
        uint256[] calldata _tokenids,
        uint256[] calldata _amounts,
        bytes memory _data
    ) public override nonReentrant returns (bytes4) {
        require(msg.sender == address(osContract), "Forbidden");
        require(bridgingEnabled, "Bridging is stopped");

        for (uint256 i = 0; i < _tokenids.length; i++) {
	        triggerReceived1155(_receiver, _tokenids[i]);
	        emit ReceivedFromOS(msg.sender, _receiver, _tokenids[i], _amounts[i]);
        }
        return super.onERC1155BatchReceived(_sender, _receiver, _tokenids, _amounts, _data);
    }

    /***********External**************/

    function claim(
        uint256 _oldId,
        uint16 _newId,
        bytes32 _leaf,
        bytes32[] calldata _merkleProof
    ) external nonReentrant {
        require(bridgingEnabled, "Bridging is stopped");
        require(address(bonesContract) != address(0), "Invalid bonesContract");

        //construct merkle node
        bytes32 node = keccak256((abi.encodePacked(_oldId.toString(), _newId.toString())));

        require(node == _leaf, "Leaf not matching the node");
        require(MerkleProof.verify(_merkleProof, merkleRoot, _leaf), "Invalid proof.");

        require(idsAndSenders[_oldId] == msg.sender, "Not owner of OS id");

        totalBridged++;
        idsBridged.push(_newId);
        oldsIdsBridgedBySender[msg.sender].push(_oldId);

        mintOnClaiming(msg.sender, _newId);
    }

    function mint721(uint16 _tokenId, address _to) external onlyOwner {
        require(_to != address(0), "Mint to address 0");
        require(!bonesContract.exists(_tokenId), "Token exists");

        if (bonesContract.exists(_tokenId) && bonesContract.ownerOf(_tokenId) == address(this)) {
            bonesContract.safeTransferFrom(address(this), _to, _tokenId);
            return;
        }
        _mint721(_tokenId, _to);
    }

    function transfer721(uint256 _tokenId, address _owner) external onlyOwner {
        require(_owner != address(0), "Can not send to address 0");
        bonesContract.safeTransferFrom(address(this), _owner, _tokenId);
    }

    /***********Private**************/


    function _mint721(uint16 _tokenId, address _owner) private {
        bonesContract.migrate(_owner, uint16(_tokenId));
        emit Minted721(_owner, _tokenId);
    }

    function triggerReceived1155(address _sender, uint256 _tokenId) internal {
        require(_sender != address(0), "Update from address 0");

        idsReceived.push(_tokenId);
        idsAndSenders[_tokenId] = _sender;
        sendersAndIds[_sender].push(_tokenId);
    }

    function mintOnClaiming(address _sender, uint16 _tokenId) internal returns (bool) {
        require(_sender != address(0), "Can not mint to address 0");
        require(_tokenId != 0, "New token id !exists");

        require(!bonesContract.exists(_tokenId), "Token already minted");

        bonesContract.migrate(_sender, _tokenId);
        emit Minted721(_sender, _tokenId);
        return true;
    }

    /***********Setters**************/

    function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
        merkleRoot = _merkleRoot;
    }

    function setbonesContract(address _contract) external onlyOwner {
        require(_contract != address(0), "_contract !address 0");
        bonesContract = BonesHeritageI(_contract);
    }

    function setOSContract(address _contract) external onlyOwner {
        require(_contract != address(0), "_contract !address 0");
        osContract = IERC1155(_contract);
    }

    /***********Views**************/

    function checkBalance(address _collector, uint256 _tokenId) external view returns (uint256) {
        require(_collector != address(0), "_collector is address 0");
        return osContract.balanceOf(_collector, _tokenId);
    }


    function getTransferredByCollector(address _collector) external view returns (uint256[] memory) {
        require(_collector != address(0), "_collector is address 0");
        return sendersAndIds[_collector];
    }

    function getBridgedByCollector(address _collector) external view returns (uint256[] memory) {
        require(_collector != address(0), "_collector is address 0");
        return oldsIdsBridgedBySender[_collector];
    }

    /***********Getters**************/

    function getTokenBridgedCount() external view returns (uint128) {
        return totalBridged;
    }

    function getBridgedTokens() external view returns (uint16[] memory) {
        return idsBridged;
    }

    function getIdsTransfered() external view returns (uint256[] memory) {
        return idsReceived;
    }

    function getbonesContract() external view returns (address) {
        return address(bonesContract);
    }

    function getOSContract() external view returns (address) {
        return address(osContract);
    }